<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Orderexcel extends CI_Controller
{
    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *        http://example.com/index.php/welcome
     *    - or -
     *        http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    function __construct()
    {
        parent::__construct();
        $this->load->model('Function_m', 'fun');
        $this->load->model('Orderexcel_m', 'm');
        $this->load->model('Order_m', 'order');
        $this->load->library('amazondata');
        $this->pageSize = $this->config->item('pagenum');
    }
    //交运订单对账
    public function doBillWithExpress(){
        if($this->input->post()){
            //暂时先测一个E邮宝
            require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
            //导出excel
            $params = $this->input->post('outExcel');
            if($params=="outExcel"){
                $objExcel = new PHPExcel();
                $total_money = $this->input->post('total_money');
                $fuman_money = $this->input->post('fuman_money');
                $chajia_money = $this->input->post('chajia_money');
                $arr_id = explode(",",$this->input->post('id_str'));
                //print_r($arr_id);exit;
                $arr_deliverNumber = explode(",",$this->input->post('deliverNumber_str'));
                $arr_deliverWeight = explode(",",$this->input->post('deliverWeight_str'));
                $arr_deliverFee = explode(",",$this->input->post('deliverFee_str'));
                $arr_fee = explode(",",$this->input->post('fee_str'));
                $arr_orderId = explode(",",$this->input->post('orderId_str'));
                $arr_weight = explode(",",$this->input->post('weight_str'));
                //自定义 长 宽
                $objExcel->setActiveSheetIndex(0);
                $objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
                $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
                $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
                $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
                $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(40);
                $objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
                $objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
                $objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);

                //设置标题
                $objExcel->setActiveSheetIndex(0)->setCellValue('A1','EXCEL行号');
                $objExcel->setActiveSheetIndex(0)->setCellValue('B1','运单号');
                $objExcel->setActiveSheetIndex(0)->setCellValue('C1','重量');
                $objExcel->setActiveSheetIndex(0)->setCellValue('D1','资费');
                $objExcel->setActiveSheetIndex(0)->setCellValue('E1','复漫预计运费');
                $objExcel->setActiveSheetIndex(0)->setCellValue('F1','复漫订单号');
                $objExcel->setActiveSheetIndex(0)->setCellValue('G1','复漫实际称重重量');

                //设置标题
                $objExcel->setActiveSheetIndex(0)->setCellValue('A2','');
                $objExcel->setActiveSheetIndex(0)->setCellValue('B2','');
                $objExcel->setActiveSheetIndex(0)->setCellValue('C2','');
                $objExcel->setActiveSheetIndex(0)->setCellValue('D2',"总计：".$total_money.",复漫有运单号费用:".$chajia_money);
                $objExcel->setActiveSheetIndex(0)->setCellValue('E2',"总计:".$fuman_money);
                $objExcel->setActiveSheetIndex(0)->setCellValue('F2','');
                $objExcel->setActiveSheetIndex(0)->setCellValue('G2','');
                foreach($arr_id as $k=>$v){
                    $count = $k+3;
                    $objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$arr_id[$k]);
                    $objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$arr_deliverNumber[$k]." ");
                    $objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$arr_deliverWeight[$k]);
                    $objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$arr_deliverFee[$k]);
                    $objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$arr_fee[$k]);
                    $objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$arr_orderId[$k]." ");
                    $objExcel->setActiveSheetIndex(0)->setCellValue('G'.$count,$arr_weight[$k]);
                }
                $excel_name = date("YmdHis");
                header("Content-type:application/vnd.ms-excel;charset=gb2312");
                header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
                header('Cache-Control: max-age=0');
                $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
                $objWriter->save('php://output');
                exit;
            }
            //交运类型必须选择
            $deliverType = $this->input->post('deliverType');
            if(!$deliverType){
                echo "必须选择交运方式";exit;
            }
            if(in_array($deliverType,array(1,2,3,4,5,10,12,14))){//DHL CNE UBI YIDA 中通-------------
                $this->checkDataValidity($deliverType);
                exit;
            } 
            $arr_excel_file = $_FILES['file_excel'];
            //print_r($deliverType);exit;
            if(!empty($arr_excel_file)&&$arr_excel_file['error']==0) {
                $fileName = $arr_excel_file["name"];
                //$fileType = $arr_excel_file["type"];
                //$fileSize = $arr_excel_file["size"];
                $tmpFileName = $arr_excel_file["tmp_name"];
                //扩展名判断
                $fileExtName = explode(".", $fileName);
                $extName = $fileExtName[count($fileExtName)-1];
                if (!($extName == "xls" || $extName == "xlsx")) {
                    echo "上传的文件扩展名应该为.xls或.xlsx或.csv";
                    exit;
                }
                if ($extName == 'xlsx') {
                    $objReader = new PHPExcel_Reader_Excel2007();
                    $objExcel = $objReader->load($tmpFileName);
                } else if ($extName == 'xls') {
                    $objReader = new PHPExcel_Reader_Excel5();
                    $objExcel = $objReader->load($tmpFileName);
                } else if ($extName == 'csv') {
                    $PHPReader = new PHPExcel_Reader_CSV();
                    //默认输入字符集
                    // $PHPReader->setInputEncoding('GBK');
                    $PHPReader->setInputEncoding('utf-8');
                    //默认的分隔符
                    $PHPReader->setDelimiter(',');
                    //载入文件
                    $objExcel = $PHPReader->load($tmpFileName);
                }
                //E邮宝或cnpost
                $web_title = "";
                if($deliverType==8||$deliverType==11){
                    $web_title = "E邮宝线下上海与CNPOST交运对账";
                }
                //云途
                if($deliverType==6){
                    $web_title = "云途交运对账";
                }
                //燕文
                if($deliverType==7){
                    $web_title = "燕文交运对账";
                }
                //获取相关excel数据
                $result = $this->m->getDeliverBill($objExcel,$deliverType);

                //print_r($result);exit;
                $this->tpl->assign('web_title',$web_title);
                $this->tpl->assign('chargeslist',$result[0]);
                $this->tpl->assign('total_money',$result[1]);
                $this->tpl->assign('fuman_money',$result[2]);
                $this->tpl->assign('chajia_money',$result[3]);
                $this->tpl->display('orderexcel/chargeslist.tpl');
            }
        }else{
            $deliver_type=array(1=>"顺丰",2=>'UPS',3=>'DHL',4=>'CNE',5=>'UBI',6=>'云途交运',
            7=>'燕文交运',8=>'E邮包线下上海',9=>"无忧物流",10=>"日本邮政",11=>'CNPOST',12=>'佳成物流',14=>'中通快递',15=>'联邦快递');
            $selectMonth=array();
            for($i=0;$i>-12;$i--){
                $selectMonth[]= date("Y-m",strtotime($i." month"));
                //echo "<br />";    
            }
            $this->tpl->assign("selectMonth", $selectMonth);
            $this->tpl->assign("deliverType", $deliver_type);
            $this->tpl->display("orderexcel/expressbill.tpl");
        }

    }

    function ajaxbutton()
    {
        $op = $this->input->get_post('op');
        //海外仓导单 根据订单号判断
        if($op=="doSubmitOrderOversea"){
            $overseaOrderlist = $this->input->post("overseaorderlist"); //获取订单列表
            $deliverOversea = $this->input->post("deliveroversea"); //海外仓发货仓库
            $transportOversea = $this->input->post("transportoversea"); //海外仓货运方式
            if ($overseaOrderlist) {
                $order_id = trim($overseaOrderlist, ",");
                $arr_order_id = implode("','",explode(",", $order_id));
                $errorMsg = "";
                $sql = "SELECT * FROM db_order_list WHERE (order_status = 2 or order_status = 1 or order_status = 3) AND order_sn in ('".$arr_order_id."') ";

                $rs = $this->db->query($sql)->result_array();
                if($rs){
                    $this->load->model('Overseaapi_m','overseaapi');
                    //一号仓发货
                    if($deliverOversea==5){
                        foreach($rs as $k=>$v){
                            //一号仓发货
                            $this->db->update("db_order_list",array("shipping_status"=>5,"salesOrderId"=>null,"is_nodelivery"=>0,"order_status"=>2,"shipping_name"=>null,"shipping_id"=>0),"order_id='".$v["order_id"]."'");
                            $errorMsg .= "订单号：【".$v["order_sn"]."】发货仓库已更改为一号仓<br/>";
                            //更新日志表db_goods_log
                            $imgdata["goods_id"] = $v['order_id'];	//订单ID db_order_list
                            $imgdata["updatetime"] = date("Y-m-d H:i:s");
                            $imgdata["createUid"] = $_COOKIE['userid'];
                            $imgdata["types"] = 3;
                            $imgdata["content"] = '发货仓库已被更新为一号仓库,订单ID='.$v['order_sn'];
                            $imgdata["createUser"] =$_COOKIE['username'];
                            $this->db->insert('db_goods_log', $imgdata);
                            continue;
                        }
                    }
                    //EZGO美国仓 仅更改仓库号
                    if($deliverOversea==6){
                        foreach($rs as $k=>$v){
                            //EZGO美国仓
                            $this->db->update("db_order_list",array("shipping_status"=>3),"order_id='".$v["order_id"]."'");
                            $errorMsg .= "订单号：【".$v["order_sn"]."】发货仓库已更改为EZGO美国仓(仅更新仓库号)<br/>";
                            //更新日志表db_goods_log
                            $imgdata["goods_id"] = $v['order_id'];	//订单ID db_order_list
                            $imgdata["updatetime"] = date("Y-m-d H:i:s");
                            $imgdata["createUid"] = $_COOKIE['userid'];
                            $imgdata["types"] = 3;
                            $imgdata["content"] = '发货仓库已被更新为EZGO美国仓(仅更新仓库号),订单ID='.$v['order_sn'];
                            $imgdata["createUser"] =$_COOKIE['username'];
                            $this->db->insert('db_goods_log', $imgdata);
                            continue;
                        }
                    }
                    //英华英国仓
                    if($deliverOversea==1){
                        $storage_id = 1;
                        foreach($rs as $k=>$v){
                            if($v['country_code']=="CH"){
                                $errorMsg .= "瑞士，不能从英国仓发货";
                                continue; //直接过滤
                            }
                            if($v['salesOrderId']){
                                //英国仓发货
                                $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods b ON a.goods_id = b.goods_id WHERE a.order_id = '".$v['order_id']."'";
                                $goodslist = $this->db->query($sql_order_sell)->result_array();
                                $rs_result=$this->overseaapi->doSendGoodsByUkWarehouse($v, $goodslist,$transportOversea);
                                $errorMsg .= $rs_result;
                                continue;
                            }
                            //判断库存是否存在
                            $sql_stocks = "SELECT GROUP_CONCAT(goods_id) as goods_id,GROUP_CONCAT(goods_sn) as goods_sku,GROUP_CONCAT(goods_number) as goods_number FROM `db_order_sell` WHERE order_id = '" . $v["order_id"] . "'";
                            $rs_stocks = $this->db->get_one($sql_stocks);
                            $isque = $this->overseaapi->getStocksCounts($rs_stocks['goods_sku'],$storage_id, $rs_stocks['goods_number']);
                            if($isque==0){
                                //一号仓发货
                                // $this->db->update("db_order_list",array("shipping_status"=>5),"order_id='".$v["order_id"]."'");
                                $errorMsg .= "订单号：【".$v["order_sn"]."】英华英国仓商品库存不足<br/>";
                                continue;
                            }
                            if($isque==1){
                                //英国仓发货
                                $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods b ON a.goods_id = b.goods_id WHERE a.order_id = '".$v['order_id']."'";
                                $goodslist = $this->db->query($sql_order_sell)->result_array();
                                $rs_result=$this->overseaapi->doSendGoodsByUkWarehouse($v, $goodslist,$transportOversea);
                                $errorMsg .= $rs_result;
                                continue;
                            }

                        }
                    }
                    //英华德国仓
                    if($deliverOversea==2){
                        $storage_id = 0;
                        foreach($rs as $k=>$v){
                            if($v['country_code']=="CH"){
                                $errorMsg .= "瑞士，不能从德国仓发货";
                                continue; //直接过滤
                            }

                            if($v["salesOrderId"]){
                                //德国仓发货
                                $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods b ON a.goods_id = b.goods_id WHERE a.order_id = '".$v['order_id']."'";
                                $goodslist = $this->db->query($sql_order_sell)->result_array();
                                $rs_result=$this->overseaapi->doSendGoodsByDeWarehouse($v, $goodslist,$transportOversea);
                                $errorMsg .= $rs_result;
                                continue;
                            }
                            //判断库存是否存在
                            $sql_stocks = "SELECT GROUP_CONCAT(goods_id) as goods_id,GROUP_CONCAT(goods_sn) as goods_sku,GROUP_CONCAT(goods_number) as goods_number FROM `db_order_sell` WHERE order_id = '" . $v["order_id"] . "'";
                            $rs_stocks = $this->db->get_one($sql_stocks);
                            $isque = $this->overseaapi->getStocksCounts($rs_stocks['goods_sku'],$storage_id, $rs_stocks['goods_number']);
                            if($isque==0){
                                //一号仓发货
                                //$this->db->update("db_order_list",array("shipping_status"=>5),"order_id='".$v["order_id"]."'");
                                $errorMsg .= "订单号：【".$v["order_sn"]."】英华德国仓商品库存不足<br/>";
                                continue;
                            }
                            if($isque==1){
                                //德国仓发货
                                $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods b ON a.goods_id = b.goods_id WHERE a.order_id = '".$v['order_id']."'";
                                $goodslist = $this->db->query($sql_order_sell)->result_array();
                               
                                $rs_result=$this->overseaapi->doSendGoodsByDeWarehouse($v, $goodslist,$transportOversea);
                                $errorMsg .= $rs_result;
                                continue;
                            }

                        }
                    }
                    //EZGO美国仓
                    if($deliverOversea==3){
                        $storage_id = 2;
                        foreach($rs as $k=>$v){
                            if($v['salesOrderId']){
                                //EZGO美国仓发货
                                $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods b ON a.goods_id = b.goods_id WHERE a.order_id = '".$v['order_id']."'";
                                $goodslist = $this->db->query($sql_order_sell)->result_array();
                                $rs_result=$this->overseaapi->doSendGoodsByUsaWarehouse($v, $goodslist,$transportOversea);
                                $errorMsg .= $rs_result;
                                continue;
                            }
                            //判断库存是否存在
                            $sql_stocks = "SELECT GROUP_CONCAT(goods_id) as goods_id,GROUP_CONCAT(goods_sn) as goods_sku,GROUP_CONCAT(goods_number) as goods_number FROM `db_order_sell` WHERE order_id = '" . $v["order_id"] . "'";
                            $rs_stocks = $this->db->get_one($sql_stocks);
                            $isque = $this->overseaapi->getStocksCounts($rs_stocks['goods_sku'],$storage_id, $rs_stocks['goods_number']);
                            if($isque==0){
                                //一号仓发货
                                //$this->db->update("db_order_list",array("shipping_status"=>5),"order_id='".$v["order_id"]."'");
                                $errorMsg .= "订单号：【".$v["order_sn"]."】EZGO美国仓商品库存不足<br/>";
                                continue;
                            }
                            if($isque==1){
                                //EZGO美国仓发货
                                $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods b ON a.goods_id = b.goods_id WHERE a.order_id = '".$v['order_id']."'";
                                $goodslist = $this->db->query($sql_order_sell)->result_array();
                                $rs_result=$this->overseaapi->doSendGoodsByUsaWarehouse($v, $goodslist,$transportOversea);
                                $errorMsg .= $rs_result;
                                continue;
                            }

                        }
                    }
                    //万邑通美西仓
                    if($deliverOversea==4){
                        $storage_id = 3;
                        foreach($rs as $k=>$v){
                            //判断库存是否存在
                            $sql_stocks = "SELECT GROUP_CONCAT(goods_id) as goods_id,GROUP_CONCAT(goods_sn) as goods_sku,GROUP_CONCAT(goods_number) as goods_number FROM `db_order_sell` WHERE order_id = '" . $v["order_id"] . "'";
                            $rs_stocks = $this->db->get_one($sql_stocks);
                            $isque = $this->overseaapi->getStocksCounts($rs_stocks['goods_sku'],$storage_id, $rs_stocks['goods_number']);
                            if($isque==0){
                                //一号仓发货
                                //$this->db->update("db_order_list",array("shipping_status"=>5),"order_id='".$v["order_id"]."'");
                                $errorMsg .= "订单号：【".$v["order_sn"]."】万邑通美西仓商品库存不足<br/>";
                                continue;
                            }
                            if($isque==1){
                                //万邑通美西仓发货
                                $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods b ON a.goods_id = b.goods_id WHERE a.order_id = '".$v['order_id']."'";
                                $goodslist = $this->db->query($sql_order_sell)->result_array();
                                $rs_result=$this->overseaapi->doSendGoodsByWinitWarehouse($v, $goodslist,$transportOversea);
                                $errorMsg .= $rs_result;
                                continue;
                            }

                        }

                    }
                    //显示相关错误信息 或直接不提示
                    echo $errorMsg;exit;

                }

            }else{
                echo  "订单不存在"; exit;
            }
        }
        //撤销海外仓发货
        if($op=="cancelOrderOversea"){
            $order_id = trim($this->input->post('order_id')); //实际为order_sn
            $depose_flag = trim($this->input->post('depose')); //是否是作废提交的相关请求 若为 1 则代表作废是提交的相关请求
            if ($order_id) {
                $order_id = trim($order_id,",");
                $arr_order_id = explode(",", $order_id);
                $errorMsg = "";
                $str_conn = "";
                foreach($arr_order_id as $k=>$v){
                    $str_conn.= "'".$v."'".",";
                }
                $str_conn = trim($str_conn,",");
                $sql = "SELECT order_id,order_sn,salesOrderId,shipping_number,shipping_name,shipping_status FROM db_order_list WHERE order_sn in ($str_conn) ";
                $rs  = $this->db->query($sql)->result_array();
                if($rs){
                    $this->load->model('Deliverorder_m', 'oversea');
                    foreach($rs as $key=>$value){
                        //$value['shipping_status'] = 2;//测试英华德国仓
                        //$value['salesOrderId'] = "D17070050038"; //测试数据
                        if(!$value["salesOrderId"]){
                            $errorMsg.= "订单号:【".$value["order_sn"]."】没有海外仓发货\n";
                            continue;
                        }
                        $salesOrderId = $value["salesOrderId"];
                        //英华英国仓取消发货
                        if($value['shipping_status']==1){
                            $url = "https://yinghua.co.uk/Token";
                            //$username = "fuman";
                            //$password = "Cosplaysky2015";
                            $username = $this->config->item('ukusername');
                            $password = $this->config->item('ukpass');
                            //获取token
                            $post_data = array ("username" => $username,"password" => $password,'grant_type'=>'password');
                            $post_data = http_build_query($post_data);
                            $headers = array("Content-type: Application/x-www-form-urlencoded;charset=utf-8");
                            $post_arr_result = $this->oversea->sendCurlPostRequest($url,$post_data,$headers);
                            $post_arr_result = json_decode($post_arr_result,1);
                            $token = $post_arr_result['access_token'];

                            //正式请求 上传新订单
                            //$salesOrderId = "D17070050190";
                            $arr_order = array("SystemID"=>$salesOrderId);
                            $order_json= json_encode(array($arr_order));
                            //正式请求  删除该订单号
                            $stocks_url = "https://yinghua.co.uk/wms/Dispatches/{$salesOrderId}";
                            $header = array("Authorization: Bearer {$token}","Content-type: Application/json;charset=utf-8");
                            $res_arr = $this->oversea->sendCurlCommonRequest($stocks_url,"delete",$order_json,$header);
                            //应当返回状态 200
                            if($res_arr==200||$res_arr==204){
                                $this->db->update("db_order_list",array("shipping_number"=>null,"shipping_name"=>null,"shipping_status"=>5,"is_nodelivery"=>0,"salesOrderId"=>null),"order_sn='".$value['order_sn']."'");
                                $this->db->update("db_order_oversea",array("del_flag"=>1),"salesOrderId='".$salesOrderId."'");
                                $errorMsg.="订单号:【".$value['order_sn']."】英华英国仓取消发货成功!\n";
                                //更新日志表db_goods_log
                                $imgdata["goods_id"] = $value['order_id'];	//订单ID db_order_list
                                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                                $imgdata["createUid"] = $_COOKIE['userid'];
                                $imgdata["types"] = 3;
                                $imgdata["content"] = '英华英国仓取消发货成功,交易ID='.$value['order_sn'];
                                $imgdata["createUser"] =$_COOKIE['username'];
                                $this->db->insert('db_goods_log', $imgdata);
                            }else{
                                $errorMsg.= "订单号:【".$value['order_sn']."】英华英国仓取消发货失败!\n";
                                //更新日志表db_goods_log
                                $imgdata["goods_id"] = $value['order_id'];	//订单ID db_order_list
                                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                                $imgdata["createUid"] = $_COOKIE['userid'];
                                $imgdata["types"] = 3;
                                $imgdata["content"] = '英华英国仓取消发货失败,交易ID='.$value['order_sn'];
                                $imgdata["createUser"] =$_COOKIE['username'];
                                $this->db->insert('db_goods_log', $imgdata);

                                //作废失败时的相关操作
                                if($depose_flag==1){
                                    //设置系统Message提醒
                                    if($this->config->item('overseareceiver') && $this->config->item('overseatipopen')==1)
                                    {
                                        $randid = $this->message->getMessageNums();	//获取当前存储的条数
                                        $packingman = explode("|",$this->config->item('overseareceiver'));
                                        $packingman[] = $_COOKIE['username'];
                                        foreach($packingman as $rs)
                                        {
                                            $postMessageData["message_type"] = $this->message->getMessageType(8);	//海外仓撤单
                                            $message = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."作废订单".$value['order_sn'];
                                            $message.="，海外仓撤单失败！需人工单独处理！";
                                            $postMessageData["message"] = $message;
                                            $postMessageData["message_toName"] = $rs;
                                            $postMessageData["isread"] =  $randid;
                                            $postMessageData["url"] = '/orderlist/orderlist?kw='.$value['order_sn'];
                                            $this->fun->saveMessage($postMessageData);
                                        }

                                    }
                                    $this->db->update("db_order_oversea",array("username"=>$_COOKIE['username'],"userid"=>$_COOKIE["userid"]),"salesOrderId='".$salesOrderId."'");


                                }



                            }
                            // echo 111;exit;
                        }
                        //英华德国仓取消发货
                        if($value['shipping_status']==2){
                            $url = "https://yinghuaglobal.de/Token";
                            $username = $this->config->item('germanyusername');
                            $password = $this->config->item('germanypass');
                            //获取token
                            $post_data = array ("username" => $username,"password" => $password,'grant_type'=>'password');
                            $post_data = http_build_query($post_data);
                            $headers = array("Content-type: Application/x-www-form-urlencoded;charset=utf-8");
                            $post_arr_result = $this->oversea->sendCurlPostRequest($url,$post_data,$headers);
                            $post_arr_result = json_decode($post_arr_result,1);
                            $token = $post_arr_result['access_token'];
                            //正式请求 上传新订单
                            //$salesOrderId = "D17070050304";
                            $arr_order = array("SystemID"=>$salesOrderId);
                            $order_json= json_encode(array($arr_order));

                            $stocks_url = "https://yinghuaglobal.de/wms/Dispatches/{$salesOrderId}";
                            $header = array("Authorization: Bearer {$token}","Content-type: Application/json;charset=utf-8");
                            $res_arr = $this->oversea->sendCurlCommonRequest($stocks_url,"delete",$order_json,$header);
                            //$msg["code"] = 201;
                            //$msg["txt"] = serialize($res_arr);
                            //echo json_encode($msg); exit;

                            //$res_arr = json_decode($res_arr,1);
                            //应当返回状态 200
                            if($res_arr==200||$res_arr==204){
                                $this->db->update("db_order_list",array("shipping_number"=>null,"shipping_name"=>null,"shipping_status"=>5,"is_nodelivery"=>0,"salesOrderId"=>null),"order_sn='".$value['order_sn']."'");
                                $this->db->update("db_order_oversea",array("del_flag"=>1),"salesOrderId='".$salesOrderId."'");
                                $errorMsg.="订单号:【".$value['order_sn']."】英华德国仓取消发货成功!\n";
                                //更新日志表db_goods_log
                                $imgdata["goods_id"] = $value['order_id'];	//订单ID db_order_list
                                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                                $imgdata["createUid"] = $_COOKIE['userid'];
                                $imgdata["types"] = 3;
                                $imgdata["content"] = '英华德国仓取消发货成功,交易ID='.$value['order_sn'];
                                $imgdata["createUser"] =$_COOKIE['username'];
                                $this->db->insert('db_goods_log', $imgdata);


                            }else{
                                $errorMsg.= "订单号:【".$value['order_sn']."】英华德国仓取消发货失败!\n";
                                //更新日志表db_goods_log
                                $imgdata["goods_id"] = $value['order_id'];	//订单ID db_order_list
                                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                                $imgdata["createUid"] = $_COOKIE['userid'];
                                $imgdata["types"] = 3;
                                $imgdata["content"] = '英华德国仓取消发货失败,交易ID='.$value['order_sn'].",".$res_arr;
                                $imgdata["createUser"] =$_COOKIE['username'];
                                $this->db->insert('db_goods_log', $imgdata);


                                //作废失败时的相关操作
                                if($depose_flag==1){
                                    //设置系统Message提醒
                                    if($this->config->item('overseareceiver') && $this->config->item('overseatipopen')==1)
                                    {
                                        $randid = $this->message->getMessageNums();	//获取当前存储的条数
                                        $packingman = explode("|",$this->config->item('overseareceiver'));
                                        $packingman[] = $_COOKIE['username'];
                                        foreach($packingman as $rs)
                                        {
                                            $postMessageData["message_type"] = $this->message->getMessageType(8);	//海外仓撤单
                                            $message = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."作废订单".$value['order_sn'];
                                            $message.="，海外仓撤单失败！需人工单独处理！";
                                            $postMessageData["message"] = $message;
                                            $postMessageData["message_toName"] = $rs;
                                            $postMessageData["isread"] =  $randid;
                                            $postMessageData["url"] = '/orderlist/orderlist?kw='.$value['order_sn'];
                                            $this->fun->saveMessage($postMessageData);
                                        }

                                    }
                                    $this->db->update("db_order_oversea",array("username"=>$_COOKIE['username'],"userid"=>$_COOKIE["userid"]),"salesOrderId='".$salesOrderId."'");
                                }
                            }
                            //print_r($res_arr);exit;
                            //$msg["code"] = 201;
                            //$msg["txt"] = serialize($token);
                            //echo json_encode($msg); exit;
                        }
                        //EZGO美国仓取消发货
                        if($value['shipping_status']==3){
                            //1.美国仓  正式环境账号 测试环境已停用
                            $customerId = $this->config->item('goodscode');
                            $token = $this->config->item('usatoken');
                            //$usaSupplierCode = $this->CI->config->item('usasuppliercode');
                            //查询发货运单信息，支持批量查询
                            $url = "http://openapi.4pis.com:8080/api/service/wmc/order/deposeSmSalerOrder?token=$token&customerId=$customerId&language=zh_CN";
                            $headers= array("Content-type: Application/json;charset=utf-8");
                            $salesOrderId_arr = array("salesOrderId"=>$salesOrderId);
                            $post_data = json_encode($salesOrderId_arr);
                            $ret_arr = $this->oversea->sendCurlPostRequest($url,$post_data,$headers);
                            $ret_arr = (array) json_decode($ret_arr);
                            //print_r($ret_arr['errorMsg']);exit;
                            if($ret_arr['errorCode']==="0" || $ret_arr['errorCode']===0){
                                $this->db->update("db_order_list",array("shipping_number"=>null,"shipping_name"=>null,"shipping_status"=>5,"is_nodelivery"=>0,"salesOrderId"=>null),"order_sn='".$value['order_sn']."'");
                                $this->db->update("db_order_oversea",array("del_flag"=>1),"salesOrderId='".$salesOrderId."'");
                                $errorMsg.="订单号:【".$value['order_sn']."】EZGO美国仓取消发货成功!\n";
                                //更新日志表db_goods_log
                                $imgdata["goods_id"] = $value['order_id'];	//订单ID db_order_list
                                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                                $imgdata["createUid"] = $_COOKIE['userid'];
                                $imgdata["types"] = 3;
                                $imgdata["content"] = 'EZGO美国仓取消发货成功,交易ID='.$value['order_sn'];
                                $imgdata["createUser"] =$_COOKIE['username'];
                                $this->db->insert('db_goods_log', $imgdata);
                            }else{
                                $errorMsg.= $ret_arr['errorMsg']." "."订单号:【".$value['order_sn']."】EZGO美国仓取消发货失败!\n";
                                //更新日志表db_goods_log
                                $imgdata["goods_id"] = $value['order_id'];	//订单ID db_order_list
                                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                                $imgdata["createUid"] = $_COOKIE['userid'];
                                $imgdata["types"] = 3;
                                $imgdata["content"] = 'EZGO美国仓取消发货失败,交易ID='.$value['order_sn']." ".$ret_arr['errorMsg'].",".$ret_arr['errorCode'];
                                $imgdata["createUser"] =$_COOKIE['username'];
                                $this->db->insert('db_goods_log', $imgdata);

                                //作废失败时的相关操作
                                if($depose_flag==1){
                                    //设置系统Message提醒
                                    if($this->config->item('overseareceiver') && $this->config->item('overseatipopen')==1)
                                    {
                                        $randid = $this->message->getMessageNums();	//获取当前存储的条数
                                        $packingman = explode("|",$this->config->item('overseareceiver'));
                                        $packingman[] = $_COOKIE['username'];
                                        foreach($packingman as $rs)
                                        {
                                            $postMessageData["message_type"] = $this->message->getMessageType(8);	//海外仓撤单
                                            $message = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."作废订单".$value['order_sn'];
                                            $message.="，海外仓撤单失败！需人工单独处理！";
                                            $postMessageData["message"] = $message;
                                            $postMessageData["message_toName"] = $rs;
                                            $postMessageData["isread"] =  $randid;
                                            $postMessageData["url"] = '/orderlist/orderlist?kw='.$value['order_sn'];
                                            $this->fun->saveMessage($postMessageData);
                                        }

                                    }
                                    $this->db->update("db_order_oversea",array("username"=>$_COOKIE['username'],"userid"=>$_COOKIE["userid"]),"salesOrderId='".$salesOrderId."'");
                                }
                            }
                        }
                        //万邑通美西仓取消发货
                        if($value['shipping_status']==4){
                            //万邑通 测试账号
                            /**
                            $url = "http://erp.sandbox.winit.com.cn/ADInterface/api";
                            $username = "rebecca";
                            $password = "888";
                            $token = "89435277FA3BA272DE795559998E-";
                             * */
                            $date = date("Y-m-d H:i:s");
                            //1.万邑通美西仓  正式环境账号
                            $url = "http://api.winit.com.cn/ADInterface/api";
                            $username = $this->config->item('winitusername');
                            //$password = $this->config->item('winitpass');
                            $token = $this->config->item('winittoken');
                            //相关签名信息
                            $post_data = array();
                            $arr_order = array();
                            $arr_order["outboundOrderNum"] = $salesOrderId;
                            //请求分两步 1.提交出库单 confirmOutboundOrder  2..作废出库单 voidOutboundOrder

                            $post_data['action'] ="confirmOutboundOrder" ;
                            $post_data['app_key'] = $username;
                            $post_data['data'] = $arr_order;
                            $post_data['format'] = "json";
                            $post_data['language'] ="zh_CN";
                            $post_data['platform'] = "SELLERERP";
                            $post_data['sign_method'] = "md5";
                            $post_data['timestamp'] = $date;
                            $post_data['version'] = "1.0";
                            //上述为签名所用字段
                            $con_data = $token;
                            $con_data.= "action".$post_data['action'].
                                "app_key".$post_data['app_key'].
                                "data".json_encode($post_data['data']).
                                "format".$post_data['format'].
                                "platform".$post_data['platform'].
                                "sign_method".$post_data['sign_method'].
                                "timestamp".$post_data['timestamp'].
                                "version".$post_data['version'];
                            $con_data.= $token;
                            $sign = strtoupper(md5($con_data));
                            $post_data['sign'] = $sign;
                            $json_post = json_encode($post_data);
                            //echo $json_post;exit;
                            $post_arr_result = $this->oversea->sendCurlPostRequest($url,$json_post,$headers=array());
                            //返回值  Array ( [code] => 0 [data] => Array ( [outboundOrderNum] => WO0000002520 ) [msg] => 成功 )
                            //重复提交 Array ( [code] => 2020240140 [data] => [msg] => 当前卖家订单号与订单[WO0000002520]重复 )
                            //print_r($post_arr_result);exit;
                            if($post_arr_result['code']==0){
                                $post_data['action'] = "voidOutboundOrder";
                                //上述为签名所用字段
                                $con_data = $token;
                                $con_data.= "action".$post_data['action'].
                                    "app_key".$post_data['app_key'].
                                    "data".json_encode($post_data['data']).
                                    "format".$post_data['format'].
                                    "platform".$post_data['platform'].
                                    "sign_method".$post_data['sign_method'].
                                    "timestamp".$post_data['timestamp'].
                                    "version".$post_data['version'];
                                $con_data.= $token;
                                $sign = strtoupper(md5($con_data));
                                $post_data['sign'] = $sign;
                                $json_post = json_encode($post_data);
                                $post_arr_rs = $this->oversea->sendCurlPostRequest($url,$json_post,$headers=array());
                                //作废订单成功
                                if($post_arr_rs['code']==0){
                                    $this->db->update("db_order_list",array("shipping_number"=>null,"shipping_name"=>null,"shipping_status"=>5,"is_nodelivery"=>0,"salesOrderId"=>null),"order_sn='".$value['order_sn']."'");
                                    $this->db->update("db_order_oversea",array("del_flag"=>1),"salesOrderId='".$salesOrderId."'");
                                    $errorMsg.="订单号:【".$value['order_sn']."】万邑通美西仓取消发货成功!\n";
                                    //更新日志表db_goods_log
                                    $imgdata["goods_id"] = $value['order_id'];	//订单ID db_order_list
                                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                                    $imgdata["createUid"] = $_COOKIE['userid'];
                                    $imgdata["types"] = 3;
                                    $imgdata["content"] = '万邑通美西仓取消发货成功,交易ID='.$value['order_sn'];
                                    $imgdata["createUser"] =$_COOKIE['username'];
                                    $this->db->insert('db_goods_log', $imgdata);
                                }else{
                                    $errorMsg.= "订单号:【".$value['order_sn']."】万邑通美西仓取消发货失败!\n";
                                    //更新日志表db_goods_log
                                    $imgdata["goods_id"] = $value['order_id'];	//订单ID db_order_list
                                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                                    $imgdata["createUid"] = $_COOKIE['userid'];
                                    $imgdata["types"] = 3;
                                    $imgdata["content"] = '万邑通美西仓取消发货失败,交易ID='.$value['order_sn'];
                                    $imgdata["createUser"] =$_COOKIE['username'];
                                    $this->db->insert('db_goods_log', $imgdata);


                                    //作废失败时的相关操作
                                    if($depose_flag==1){
                                        //设置系统Message提醒
                                        if($this->config->item('overseareceiver') && $this->config->item('overseatipopen')==1)
                                        {
                                            $randid = $this->message->getMessageNums();	//获取当前存储的条数
                                            $packingman = explode("|",$this->config->item('overseareceiver'));
                                            $packingman[] = $_COOKIE['username'];
                                            foreach($packingman as $rs)
                                            {
                                                $postMessageData["message_type"] = $this->message->getMessageType(8);	//海外仓撤单
                                                $message = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."作废订单".$value['order_sn'];
                                                $message.="，海外仓撤单失败！需人工单独处理！";
                                                $postMessageData["message"] = $message;
                                                $postMessageData["message_toName"] = $rs;
                                                $postMessageData["isread"] =  $randid;
                                                $postMessageData["url"] = '/orderlist/orderlist?kw='.$value['order_sn'];
                                                $this->fun->saveMessage($postMessageData);
                                            }

                                        }
                                        $this->db->update("db_order_oversea",array("username"=>$_COOKIE['username'],"userid"=>$_COOKIE["userid"]),"salesOrderId='".$salesOrderId."'");
                                    }
                                }

                            }else{
                                $errorMsg.= "订单号:【".$value['order_sn']."】万邑通美西仓取消发货失败!\n";
                                //更新日志表db_goods_log
                                $imgdata["goods_id"] = $value['order_id'];	//订单ID db_order_list
                                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                                $imgdata["createUid"] = $_COOKIE['userid'];
                                $imgdata["types"] = 3;
                                $imgdata["content"] = '万邑通美西仓取消发货失败,交易ID='.$value['order_sn'];
                                $imgdata["createUser"] =$_COOKIE['username'];
                                $this->db->insert('db_goods_log', $imgdata);

                                //作废失败时的相关操作
                                if($depose_flag==1){
                                    //设置系统Message提醒
                                    if($this->config->item('overseareceiver') && $this->config->item('overseatipopen')==1)
                                    {
                                        $randid = $this->message->getMessageNums();	//获取当前存储的条数
                                        $packingman = explode("|",$this->config->item('overseareceiver'));
                                        $packingman[] = $_COOKIE['username'];
                                        foreach($packingman as $rs)
                                        {
                                            $postMessageData["message_type"] = $this->message->getMessageType(8);	//海外仓撤单
                                            $message = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."作废订单".$value['order_sn'];
                                            $message.="，海外仓撤单失败！需人工单独处理！";
                                            $postMessageData["message"] = $message;
                                            $postMessageData["message_toName"] = $rs;
                                            $postMessageData["isread"] =  $randid;
                                            $postMessageData["url"] = '/orderlist/orderlist?kw='.$value['order_sn'];
                                            $this->fun->saveMessage($postMessageData);
                                        }

                                    }
                                    $this->db->update("db_order_oversea",array("username"=>$_COOKIE['username'],"userid"=>$_COOKIE["userid"]),"salesOrderId='".$salesOrderId."'");
                                }
                            }
                        }

                    }
                    $msg["code"] = 200;
                    $msg["txt"] = $errorMsg;
                    echo json_encode($msg); exit;
                }else{
                    $msg["code"] = 201;
                    $msg["txt"] = "订单不存在！";
                    echo json_encode($msg);exit;
                }
            } else {
                $msg["code"] = 201;
                $msg["txt"] = "订单ID为空！";
                echo json_encode($msg);exit;
            }
        }
        //导入订单
        if($op=="importExcelOrder"){
            $token = $this->input->get('token');
            if($token){
                $userid = $_COOKIE['userid'];
                $sql = "SELECT * FROM tmp_upload_order WHERE del_flag = 0 AND token = '{$token}' AND createUid = '{$userid}' ";
                $rs  = $this->db->query($sql)->row_array();
                echo "<div style='text-align:center;font-size:24px;color:red;'>数据导入相关信息...</div>";
                echo "<br/><br/>";
                if($rs){
                    $arr_orders = unserialize($rs['orders']);
                    $arr_goods  = unserialize($rs['goods']);
                    $shopId = $arr_orders[2]['shopId']; //都是从excel第二行获取数据
                    /** 亚马逊 Amazon平台 telacos Getime  Pattistore veribuy,Mesodyn 四个店铺导单 **/
                    //$amazon_shop = array(67,343,375,410,409);
                    //雅虎店铺
                   // $yahoo_shop = array(63); //63为店铺id

                    /**
                    if(in_array($shopId,$amazon_shop)){
                        $result = $this->insertAmazonOrder($arr_orders,$token,$moneyType = "USD");exit;
                    }**/

                    //亚马逊平台
                    if($arr_orders[2]['platfrom']==2){
                        $result = $this->insertAmazonOrder($arr_orders,$token,$moneyType = "USD");
                        exit;
                    }

                    //日本雅虎
                    if ($arr_orders[2]['platfrom']==21){
                        //if (in_array($shopId,$yahoo_shop)){
                        $result = $this->insertAmazonOrder($arr_orders,$token,$moneyType = "JPY");
                        exit;
                    }

                    //淘宝 天猫相关 要统一平台
                    $taobao_shop = array(130,65,64);
                    //if(in_array($arr_orders[2]['platfrom'],array(5,6))){
                    if(in_array($shopId,$taobao_shop)){
                        //默认淘宝，天猫等平台
                        $result = $this->insertTaobaoOrder($arr_orders,$arr_goods,$token);
                        exit;
                    }

                    //台湾 Shopee平台
                    if($arr_orders[2]['platfrom']==22){
                        $result = $this->insertTaiWanOrder($arr_orders,$token,$moneyType = "TWD");
                        exit;
                    }

                    //速卖通平台
                    if($arr_orders[2]['platfrom']==10){
                        $result = $this->insertAliexpressOrder($arr_orders,$token,$moneyType = "USD");
                        exit;
                    }

                    echo "没有任何数据被上传了！";exit;   //默认


                    /**
                    if(in_array($shopId,$amazon_shop)){
                        $result = $this->insertAmazonOrder($arr_orders,$token,$moneyType = "USD");
                    }elseif (in_array($shopId,$yahoo_shop)){
                        $result = $this->insertAmazonOrder($arr_orders,$token,$moneyType = "JPY");
                    }else{
                        //默认淘宝，天猫等平台
                        $result = $this->insertTaobaoOrder($arr_orders,$arr_goods,$token);
                    }
                     * */
                }else{
                    $userid = $_COOKIE['userid'];
                    $sql_reason = "SELECT * FROM tmp_upload_order WHERE del_flag = 1 AND token = '{$token}' AND createUid = '{$userid}' ";
                    $rs_reason  = $this->db->query($sql_reason)->row_array();
                    if($rs_reason){
                        echo "该文件已经上传";exit;
                    }else{
                        echo "上传失败";exit;
                    }
                }
            }else{

                //追加一个删除临时表记录选项
                $totalCount = $this->db->count_all_results('tmp_upload_order');
                if($totalCount>=1000){
                    $tmp_sql = "DELETE FROM tmp_upload_order LIMIT 980 ";
                    $this->db->query($tmp_sql); //删除之前980条数据，保留20条最新数据
                }

                //界面显示相关导入信息
                require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
                $shopName = trim($this->input->post('shopName'));

                $platformId = trim($this->input->post('platformId')); //所选择的平台id
                //判断 是否支持该平台店铺的excel导入功能
                // 平台id    5 淘宝  6 天猫  2 亚马逊  21 日本雅虎  22 台湾shopee 10为速卖通
                $arr_platform = array(2,5,6,21,22,10);
                if(!in_array($platformId,$arr_platform)){
                    echo "不支持该平台所属店铺的excel导入功能!";exit;
                }
                //添加填写店铺名功能
                if($shopName){
                    $sql = "SELECT * FROM d_shop WHERE name = '{$shopName}' ";
                    $arr_shop  = $this->db->query($sql)->row_array();
                    if(!$arr_shop){
                        echo "该店铺不存在！";exit;
                    }
                    if(!in_array($arr_shop['platfrom'],$arr_platform)){
                        echo "不支持该平台所属店铺的excel导入功能!";exit;
                    }
                    $shopId = $arr_shop['id'];
                }else{
                    //店铺必须选择
                    $shopId = $this->input->post('shopId'); //店铺id
                    $sql = "SELECT * FROM d_shop WHERE id = '{$shopId}' AND platfrom = '{$platformId}' ";
                    $arr_shop  = $this->db->query($sql)->row_array();
                    if(!$arr_shop){
                        echo "未选择店铺名或该店铺不存在！";exit;
                    }
                }
                $arr_excel_file = $_FILES['file_excel'];
                if(!empty($arr_excel_file)&&$arr_excel_file['error']==0){
                    $fileName = $arr_excel_file["name"];
                    $tmpFileName = $arr_excel_file["tmp_name"];
                    //扩展名判断
                    $fileExtName = explode(".",$fileName);
                    $extName = $fileExtName[count($fileExtName)-1];
                    if(!($extName=="xls"||$extName=="xlsx")){
                        echo "上传的文件扩展名应该为.xls或.xlsx或.csv";exit;
                    }
                    if ($extName =='xlsx') {
                        $objReader = new PHPExcel_Reader_Excel2007();
                        $objExcel = $objReader ->load($tmpFileName);
                    } else if ($extName =='xls') {
                        $objReader = new PHPExcel_Reader_Excel5();
                        $objExcel = $objReader ->load($tmpFileName);
                    } else if ($extName=='csv') {
                        $PHPReader = new PHPExcel_Reader_CSV();
                        $PHPReader->setInputEncoding('utf-8');
                        //默认的分隔符
                        $PHPReader->setDelimiter(',');
                        $objExcel = $PHPReader->load($tmpFileName);
                    }
                    $import_flag = 1;
                    /** 亚马逊 Amazon平台 telacos Getime  Pattistore veribuy四个店铺导单 **/

                    /**已经通过平台方式判断了 见下文
                    $amazon_shop = array(67,343,375,410,63,409); //其中 13 为日本雅虎平台 63为店铺id，同样的excel格式
                    if(in_array($shopId,$amazon_shop)){
                        $result = $this->importAmazonOrder($objExcel,$arr_shop);
                        exit;
                    }**/

                    //亚马逊平台 针对所以亚马逊平台
                    if(in_array($arr_shop['platfrom'],array(2,21))){ //21为日本雅虎平台与亚马逊共用一个模板，然后在区分
                        $result = $this->importAmazonOrder($objExcel,$arr_shop);
                        exit;
                    }

                    //淘宝 天猫平台
                    if(in_array($arr_shop['platfrom'],array(5,6))){
                        $result = $this->importTaobaoOrder($objExcel,$arr_shop);
                        exit;
                    }
                    //台湾Shopee平台
                    if(in_array($arr_shop['platfrom'],array(22))){
                        $result = $this->importTaiWanOrder($objExcel,$arr_shop);
                        exit;
                    }

                    //速卖通平台
                    if(in_array($arr_shop['platfrom'],array(10))){
                        $result = $this->importAliexpressOrder($objExcel,$arr_shop);
                        exit;
                    }

                    /**
                    $taobao_shop = array(130,65,64);
                    if(in_array($shopId,$taobao_shop)){
                        /**  淘宝平台 Taobao3  COSSKY 店铺  Tmall平台 COSMORE店铺导单 */
                   //     $result = $this->importTaobaoOrder($objExcel,$arr_shop);
                   //     exit;
                   // }

                    //若不存在该excel导入情况
                    if($import_flag==1){
                        echo "不存在该店铺的导入excel格式，请联系管理员设置!";exit;
                    }

                }else{
                    echo "未上传任何文件";exit;
                }
            }
            //print_r($sheet);exit;
        }
        if($op=="getShopNames"){
            $platformId = $this->input->post('platformId');
            $sql = "SELECT id,name FROM d_shop WHERE platfrom = '".$platformId."'";
            $rs  = $this->db->query($sql)->result_array();
            echo json_encode($rs);exit;
        }

    } 
    /** 亚马逊 Amazon平台 telacos Getime  Pattistore veribuy四个店铺导单 **/
    private function importAmazonOrder($objExcel,$arr_shop){
        $sheet = $objExcel->getSheet(0);
        $rows = $sheet->getHighestRow(); //多少行数据
        $cols = $sheet->getHighestColumn();
        $arrCellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
            'AV','AW','AX','AY','AZ','BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT');
        $columns = array_search($cols, $arrCellName); //获取数组下标最大数
        $rand = date("YmdHis").rand(111111,999999);
        $rand = md5($rand);
        //行
        echo "<div style=\"color:red;\">需要更新的订单信息为...</div>";
        $url = "/orderexcel/ajaxbutton?op=importExcelOrder&token=".$rand;
        echo "<a href='$url'>点击确定上传</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='/orderlist/orderlist'>返回修改后上传</a>";
        echo "<br/>";
        echo "<table>";
        $tr_title="<tr><td>order-id</td><td>order-item-id</td><td>purchase-date</td><td>payments-date</td><td>buyer-email</td><td>buyer-name</td>";
        $tr_title.="<td>buyer-phone-number</td><td>sku</td><td>product-name</td><td>quantity-purchased</td><td>currency</td><td>shipping-price</td><td>item-price</td>";
        $tr_title.="<td>recipient-name</td><td>ship-address-1</td><td>ship-address-2</td><td>ship-address-3</td>";
        $tr_title.="<td>ship-city</td><td>ship-state</td><td>ship-postal-code</td><td>ship-country</td><td>ship-phone-number</td>";
        $tr_title.="</tr>";
        echo $tr_title;
        for($row=2;$row<=$rows;$row++){
            echo "<tr>";
            //列
            for($column=0;$column<= $columns;$column++){
                $cellValue = $arrCellName[$column].$row;
                //当前数据名称
                $dataName = $arrCellName[$column]."1";
                $dataName= $sheet->getCell($dataName)->getValue();

                //获取一行每列的值
                $col_val = $sheet->getCell($cellValue)->getValue();
                //店铺相关
                $arr_order[$row]['shopId'] = $arr_shop['id'];
                $arr_order[$row]['shopName'] = $arr_shop['name'];
                $arr_order[$row]['oper'] = $arr_shop['updateoper']; //店铺负责人
                $arr_order[$row]['platfromname'] = $arr_shop['platfromname']; //平台名
                $arr_order[$row]['platfrom'] = $arr_shop['platfrom']; //平台id
                //订单编号
                if($dataName=="order-id"){
                    $order_sn = trim($col_val);
                    echo "<td>$order_sn</td>";
                    $arr_order[$row]['order_sn'] = $order_sn;
                }
                //商品id
                if($dataName=="order-item-id"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['productId'] = $col_val;
                }
                //购买日期
                if($dataName=="purchase-date"){
                    echo "<td>$col_val</td>";
                }
                //付款日期
                if($dataName=="payments-date"){
                    $date_value = $sheet->getCell($arrCellName[$column].$row)->getFormattedValue();
                    $times = strtotime($date_value);
                    $dates = date("Y-m-d H:i:s",$times);
                    echo "<td>$dates</td>";
                    if($date_value){
                        $pay_date = date("Y-m-d H:i:s",strtotime(trim($col_val)));
                    }else{
                        $pay_date = date("Y-m-d H:i:s");
                    }

                    $arr_order[$row]['ordertime'] = $dates;
                }
                //买家电子邮件
                if($dataName=="buyer-email"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['email'] = $col_val;
                }
                //买家姓名
                if($dataName=="buyer-name"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['consignee'] = $col_val;
                }
                //买家电话
                if($dataName=="buyer-phone-number"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['tel'] = $col_val;
                }
                //sku
                if($dataName=="sku"){
                    echo "<td>$col_val</td>";
                    $arr_sku = explode("@",$col_val);
                    $arr_order[$row]['goods_sn'] = trim($arr_sku[0]);
                }
                //商品名称
                if($dataName=="product-name"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['goods_name'] = $col_val;
                }
                //购买数量
                if($dataName=="quantity-purchased"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['goods_number'] = $col_val;
                }
                //货币
                if($dataName=="currency"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['currency'] = $col_val;
                }
                //商品价格
                if($dataName=="item-price"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['goods_price'] = $col_val;
                }
                //运费
                if($dataName=="shipping-price"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['shipping_fee'] = $col_val;
                }
                //收件人姓名
                if($dataName=="recipient-name"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['consignee'] = $col_val;
                }
                //收件人地址
                if($dataName=="ship-address-1"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['address'] = $col_val;
                }
                //收件人地址
                if($dataName=="ship-address-2"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['address2'] = $col_val;
                }
                //收件人地址
                if($dataName=="ship-address-3"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['address3'] = $col_val;
                }
                if($dataName=="ship-city"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['city'] = $col_val;
                }
                if($dataName=="ship-state"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['province'] = $col_val;
                }
                if($dataName=="ship-postal-code"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['zipcode'] = $col_val;
                }
                if($dataName=="ship-country"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['country_code'] = $col_val;
                }
                if($dataName=="ship-phone-number"){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['tel'] = $col_val;
                }
            }
            //更新或插入数据库表记录
            echo "<tr/>";
            // print_r($arr_row);exit;
        }
        echo "<table>";
        echo "<br/>";
        echo "<br/>";
        echo "<a href='$url'>点击确定上传</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='/orderlist/orderlist'>返回修改后上传</a>";
        echo "<br/><br/>";
        //更新数据库相关表
        $data['orders'] = serialize($arr_order);
        //$data['goods'] = serialize($arr_goods); 都在订单表里面
        $data['createUid'] = $_COOKIE['userid'];
        $data['createUser'] = $_COOKIE['username'];
        $data['addTime']= date("Y-m-d H:i:s");
        $data['timeOut'] = time()+7200; //过期时间 两小时
        //$data['isUpload']  = 0;//默认0，若为1则代表真实上传过
        //$data['del_flag'] = 0; //默认
        $data['token'] = $rand;
        $this->db->insert('tmp_upload_order',$data);
    }
    private function insertAmazonOrder(& $arr_orders,$token,$moneyType){
        $this->load->library('amazondata');
        //这个四个店铺 都是 美国的 查询汇率
        $sql_rate = "SELECT * FROM d_moneyrate WHERE name = '{$moneyType}' ";
        $rs_rate  = $this->db->query($sql_rate)->row_array();
        //循环订单列表
        foreach($arr_orders as $k=>$v){
            $order_row = $k-1;
            $arr_good  = array();
            $arr_order = array();
            //若存在，则更新，否则插入
            $sql_order = "SELECT * FROM db_order_list WHERE tradeid = '{$v['order_sn']}' ";
            $rs_order  = $this->db->query($sql_order)->row_array();
            try {
                $this->db->trans_begin();
                if(!$v['order_sn']){
                    continue;
                }
                if ($rs_order) {
                    //更新商品表
                    $sql_goods = "SELECT * FROM db_order_sell WHERE goods_sn = '{$v['goods_sn']}' AND order_id = {$rs_order['order_id']} ";
                    $rs_goods = $this->db->query($sql_goods)->row_array();
                    if($rs_goods){
                        continue;
                    }else{
                        $rs_rate['rate'] = $rs_order['moneyrate'];
                        //判断goods_sn是否存在
                        $goods_sql = "SELECT * FROM db_goods WHERE goods_sku = '{$v['goods_sn']}' ";
                        $goods_rs  = $this->db->query($goods_sql)->row_array();
                        if(!$goods_rs){
                            if ($v['shipping_fee']) {
                                $shipping_originask = $v['shipping_fee']+$rs_order['shipping_originask'];//原始快递费
                                $shipping_fee = $shipping_originask*$rs_rate['rate']; //收取客人快递费RMB
                                $this->db->update('db_order_list',array('order_status'=>7,"shipping_fee"=>$shipping_fee,"shipping_originask"=>$shipping_originask),array('tradeid'=>$v['order_sn']));
                            }else{
                                $this->db->update('db_order_list',array('order_status'=>7),array('tradeid'=>$v['order_sn']));
                            }
                        }else{

                            if ($v['shipping_fee']) {
                                $shipping_originask = $v['shipping_fee']+$rs_order['shipping_originask'];//原始快递费
                                $shipping_fee = $shipping_originask*$rs_rate['rate']; //收取客人快递费RMB
                                $this->db->update('db_order_list',array("shipping_fee"=>$shipping_fee,"shipping_originask"=>$shipping_originask),array('tradeid'=>$v['order_sn']));
                            }
                            $arr_good['goods_id'] = $goods_rs['goods_id'];
                            $arr_good['goods_weight'] = $goods_rs['g_weight']*$v['goods_number'];
                            $arr_good['originsku'] = $goods_rs['goods_parent_sku'];

                            $weight = $arr_good['goods_weight'];
                            $sql_upd = "UPDATE db_order_list SET orderweight = orderweight+$weight WHERE tradeid = '{$v['order_sn']}' ";
                            $upd_rs = $this->db->query($sql_upd);


                            //获取商品的成本价格
                            $factorycode = $this->amazondata->factorycode();
                            $costprice = 0;
                            if(is_numeric($v['goods_sn'])&&preg_match('|^\d{8}$|',$v['goods_sn'])){
                                $goodscode = substr($v['goods_sn'],0,2);
                                if(in_array($goodscode,$factorycode)){
                                    $costprice = $goods_rs['g_costprice'];
                                }
                            }else{
                                //如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
                                if(is_numeric($goods_rs["goods_parent_sku"]) && preg_match('|^\d{8}$|',$goods_rs["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
                                {
                                    $goodscodes  = substr($goods_rs["goods_parent_sku"],0,2);//取开头2位数
                                    if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
                                    {
                                        $costprice = $goods_rs["bulkprice"];	//批量按关联价计算
                                    }
                                }else{
                                    $costprice = $goods_rs["g_costprice"];
                                }
                            }
                        }
                        if(!$costprice){
                            $costprice = 0;
                        }
                        $arr_good['costprice'] = $costprice;
                        //插入相关商品表
                        $arr_good['order_id'] = $rs_order['order_id'];
                        if($v['goods_name']){
                            $arr_good['goods_name'] = $v['goods_name'];
                        }
                        if(trim($v['productId'])){
                            $arr_good['productId'] = $v['productId'];
                        }
                        if($v['goods_price']){
                            $arr_good['goods_price'] = $v['goods_price'];
                        }else{
                            $arr_good['goods_price'] = 0;
                        }
                        $arr_good['goods_amount'] = $v['goods_price']*$rs_rate['rate'];;
                        $arr_good['goods_number'] = $v['goods_number'];
                        $arr_good['goods_sn'] = $v['goods_sn'];

                        //若为日本yahoo网站的订单，则要将商品价格平均开来
                        if($moneyType=="JPY"){
                            $total_price = $rs_order['goods_originask']+$arr_good['goods_price'];
                            $total_amount = $rs_order['goods_amount']+$arr_good['goods_amount'];
                            //更新订单
                            $this->db->update("db_order_list",array("goods_originask"=>$total_price,"goods_amount"=>$total_amount)," order_id ='".$rs_order['order_id']."'");
                        }

                        $this->db->insert('db_order_sell', $arr_good);
                    }
                } else {
                    //$this->load->library('amazondata');
                    $arr_order['order_sn'] = $this->amazondata->getNo("",$v['order_sn']);//生成订单序号
                    //插入订单表
                    $arr_order['tradeid'] = $v['order_sn']; //tradeid
                    //固定order_status
                    $arr_order['dates'] = date("Y-m-d");
                    $arr_order['order_source'] = "正常订单";
                    $arr_order['order_status'] = 2; //已支付

                    $arr_order['moneyrate'] = $rs_rate['rate']; //当前相当于人民币汇率
                    if ($v['platfrom']) {
                        $arr_order['platformID'] = $v['platfrom'];
                    }

                    $arr_order['platform_message'] = NULL; //默认

                    //美国 几个店铺都是美国的
                    if($moneyType=="USD"){
                        $arr_order['country_cn'] = "美国";
                        $arr_order['country'] = "UNITED STATES";
                        $arr_order['country_code'] = "US";
                        $arr_order['saleschannel'] = "amazon";
                    }
                    if($moneyType=="JPY"){
                        $arr_order['country_cn'] = "日本";
                        $arr_order['country'] = "JAPAN";
                        $arr_order['country_code'] = "JP";
                        $arr_order['shipping_status'] = 5; //默认走一号仓
                        $arr_order['saleschannel'] = "JP-Yahoo";
                    }

                    if($v['currency']){
                        $arr_order['moneytype'] = $v['currency'];
                    }
                    $arr_order['add_time'] = time();
                    //店铺
                    $arr_order['shopid'] = $v['shopId'];
                    $sql = "SELECT * FROM d_shop WHERE id = '{$v['shopId']}' ";
                    $rs_shop = $this->db->query($sql)->row_array();
                    if($rs_shop["shop_platform_fee"]>0)
                    {
                        $shop_platform_fee  =$rs_shop["shop_platform_fee"];
                    }else{
                        $shop_platform_fee = 0.15;
                    }
                    if($rs_shop["shop_pay_fee"]>0)
                    {
                        $shop_pay_fee  =$rs_shop["shop_pay_fee"];
                    }else{
                        $shop_pay_fee = 0.015;
                    }

                    $arr_order['shopname'] = $v['shopName'];
                    if($v['oper']){
                        $arr_order['shopoper'] = $v['oper'];
                    }
                    if ($v['platfromname']) {
                        $arr_order['platform_message'] = $v['platfromname']; //亚马逊平台
                    }
                    if ($v['email']) {
                        $arr_order['email'] = $v['email'];
                    }
                    if ($v['city']) {
                        $arr_order['city'] = $v['city'];
                    }
                    if ($v['province']) {
                        $arr_order['province'] = $v['province'];
                    }
                    if ($v['zipcode']) {
                        $arr_order['zipcode'] = $v['zipcode'];
                    }
                    if ($v['country_code']) {
                        $arr_order['country_code'] = $v['country_code'];
                    }
                    if ($v['consignee']) {
                        $arr_order['customerid'] = $v['consignee'];
                    }
                    if ($v['shipping_fee']) {
                        $arr_order['shipping_fee'] = $v['shipping_fee']*$rs_rate['rate']; //收取客人快递费RMB
                        $arr_order['shipping_originask'] = $v['shipping_fee'];//原始快递费
                    }
                    if ($v['goods_price']) {
                        $arr_order['goods_originask'] = $v['goods_price'];
                        $arr_order['goods_amount'] = $v['goods_price']*$rs_rate['rate'];
                        //平台交易费
                        $arr_order['platform_fee'] = $arr_order['goods_amount']*$shop_platform_fee; //商品总金额的15% 亚马逊 日本都那么多
                        $arr_order['pay_fee'] = $arr_order['goods_amount']*$shop_pay_fee;
                    }
                    if ($v['consignee']) {
                        $arr_order['consignee'] = $v['consignee'];
                    }
                    if ($v['address']) {
                        //对地址进行截取
                        $arr_order['address'] = $v['address'];
                    }
                    if ($v['address2']) {
                        //对地址进行截取
                        $arr_order['address2'] = $v['address2'];
                    }
                    if ($v['address3']) {
                        //对地址进行截取
                        $arr_order['address2'] .= $v['address3'];
                    }
                    if ($v['tel']) {
                        $arr_order['tel'] = $v['tel'];
                    }
                    if ($v['ordertime']) {
                        $arr_order['ordertime'] = $v['ordertime'];
                    }
                    $this->db->insert('db_order_list', $arr_order);
                    $insert_id = $this->db->insert_id();

                    //更新日志表db_goods_log
                    $imgdata["goods_id"] = $insert_id;	//订单ID db_order_list
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = $_COOKIE['userid'];
                    $imgdata["types"] = 3;
                    //$imgdata["content"] = 'excel导入订单，订单id为：'.$insert_id;
                    $imgdata["content"] = 'excel导入订单，交易ID='.$arr_order['tradeid'];
                    $imgdata["createUser"] =$_COOKIE['username'];
                    $this->db->insert('db_goods_log', $imgdata);

                    //插入商品表
                    if ($insert_id) {
                            //判断goods_sn是否存在
                            $goods_sql = "SELECT * FROM db_goods WHERE goods_sku = '{$v['goods_sn']}' ";
                            $goods_rs  = $this->db->query($goods_sql)->row_array();
                            if(!$goods_rs){
                                $this->db->update('db_order_list',array('order_status'=>7),array('tradeid'=>$v['order_sn']));
                            }else{
                                $arr_good['goods_id'] = $goods_rs['goods_id'];
                                $arr_good['goods_weight'] = $goods_rs['g_weight']*$v['goods_number'];
                                $arr_good['originsku'] = $goods_rs['goods_parent_sku'];

                                $weight = $arr_good['goods_weight'];
                                $sql_upd = "UPDATE db_order_list SET orderweight = orderweight+$weight WHERE tradeid = '{$v['order_sn']}' ";
                                $upd_rs = $this->db->query($sql_upd);

                                //获取商品的成本价格
                                $factorycode = $this->amazondata->factorycode();
                                if(is_numeric($v['goods_sn'])&&preg_match('|^\d{8}$|',$v['goods_sn'])){
                                    $goodscode = substr($v['goods_sn'],0,2);
                                    if(in_array($goodscode,$factorycode)){
                                        $costprice = $goods_rs['g_costprice'];
                                    }
                                }else{
                                    //如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
                                    if(is_numeric($goods_rs["goods_parent_sku"]) && preg_match('|^\d{8}$|',$goods_rs["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
                                    {
                                        $goodscodes  = substr($goods_rs["goods_parent_sku"],0,2);//取开头2位数
                                        if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
                                        {
                                            $costprice = $goods_rs["bulkprice"];	//批量按关联价计算
                                        }
                                    }else{
                                        $costprice = $goods_rs["g_costprice"];
                                    }
                                }
                                $arr_good['costprice'] = $costprice;
                            }
                            if(!$arr_good['costprice']){
                                $arr_good['costprice'] = 0;
                            }

                            //插入相关商品表
                            $arr_good['order_id'] = $insert_id;
                            if($v['goods_name']){
                                $arr_good['goods_name'] = $v['goods_name'];
                            }
                            if(trim($v['productId'])){
                                $arr_good['productId'] = $v['productId'];
                            }
                            if($v['goods_price']){
                                $arr_good['goods_price'] = $v['goods_price'];
                            }
                            $arr_good['goods_amount'] = $v['goods_price']*$rs_rate['rate'];
                            $arr_good['goods_number'] = $v['goods_number'];
                            $arr_good['goods_sn'] = $v['goods_sn'];

                            $this->db->insert('db_order_sell', $arr_good);
                    }
                    echo "<div style='text-align:center;font-size:12px;'>第" . $order_row . "个订单以及其商品插入完成,订单号：{$v['order_sn']}</div>";
                    echo "<br/>";
                }
                //$this->db->trans_commit();
            }catch(Exception $e){
                //$this->db->trans_rollback();
                echo "<div style='text-align:center;font-size:12px;color:red;'>第" . $order_row . "个订单以及其商品插入或更新失败".$e->getMessage()."订单号：".$v['order_sn']."</div>";
            }
            //若执行成功，则提交

            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
            }
            else
            {
                $this->db->trans_commit();
            }

        }
        echo "<div style='text-align:center;font-size:24px;color:red;'>数据导入完成...</div>";
        echo "<br/>";
        //更新 isUpload 说明已上传  del_flag 删除标记
        $this->db->update('tmp_upload_order',array('isUpload'=>1,'del_flag'=>1),array('token'=>$token));
    }
    /**  淘宝平台 Taobao3  COSSKY 店铺  Tmall平台 COSMORE店铺导单 */
    private function importTaobaoOrder($objExcel,$arr_shop){
        $sheet = $objExcel->getSheet(0);
        $rows = $sheet->getHighestRow(); //多少行数据
        $cols = $sheet->getHighestColumn();
        $arrCellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
            'AV','AW','AX','AY','AZ','BA','BB','BC','BD','BE','BF');
        $columns = array_search($cols, $arrCellName); //获取数组下标最大数
        $rand = date("YmdHis").rand(111111,999999);
        $rand = md5($rand);
        //行
        echo "<div style=\"color:red;\">需要更新的订单信息为...</div>";
        $url = "/orderexcel/ajaxbutton?op=importExcelOrder&token=".$rand;
        echo "<a href='$url'>点击确定上传</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='/orderlist/orderlist'>返回修改后上传</a>";
        echo "<br/>";
        echo "<table>";
        $tr_title="<tr><td>订单编号</td><td>买家会员名</td><td>买家支付宝账号</td><td>买家应付货款</td><td>买家应付邮费</td><td>总金额</td>";
        $tr_title.="<td>买家实际支付金额</td><td>订单状态</td><td>买家留言</td><td>收货人姓名</td><td>收货地址 </td><td>运送方式 </td><td>联系电话</td>";
        $tr_title.="<td>联系手机</td><td>订单创建时间</td><td>订单付款时间</td><td>物流单号</td><td>物流公司</td><td>订单备注</td>";
        $tr_title.="<td>店铺Id</td><td>店铺名称</td>";
        $tr_title.="</tr>";
        echo $tr_title;
        for($row=2;$row<=$rows;$row++){
            echo "<tr>";
            $fund_status = 0; //判断是否付款
            //列
            for($column=0;$column<= $columns;$column++){
                $cellValue = $arrCellName[$column].$row;
                //获取一行每列的值
                $col_val = $sheet->getCell($cellValue)->getValue();
                //店铺相关
                $arr_row[$row]['shopId'] = $arr_shop['id'];
                $arr_row[$row]['shopName'] = $arr_shop['name'];
                $arr_row[$row]['oper'] = $arr_shop['updateoper']; //店铺负责人
                $arr_row[$row]['platfromname'] = $arr_shop['platfromname']; //平台名
                $arr_row[$row]['platformID'] = $arr_shop['platfrom']; //平台id

                $arr_order[$row]['platfrom'] = $arr_shop['platfrom']; //平台id 判断是需要，跟其他保持一致


                //订单编号.
                if($column==0){
                    $order_sn = trim($col_val,"=");
                    echo "<td>$order_sn</td>";
                    $arr_row[$row]['order_sn'] = trim($col_val,"=");
                    $arr_row[$row]['order_sn'] = trim($arr_row[$row]['order_sn'],'"');
                }
                //客户登录id --买家会员名
                if($column==1){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['customerid'] = $col_val;
                }
                //买家支付宝账户
                if($column==2){
                    echo "<td>$col_val</td>";
                }
                //买家应付货款
                if($column==3){
                    echo "<td>$col_val</td>";
                    //$arr_row['shipping_realfee'] = $col_val;
                }
                //买家应付邮费
                if($column==4){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['shipping_originask'] = $col_val;
                    $arr_row[$row]['shipping_fee'] = $col_val;
                }
                //$column==5 //买家支付积分
                //总金额 商品总金额
                if($column==6){
                    //总金额
                    echo "<td>$col_val</td>";
                    //商品金额
                    $goods_amount = $col_val-$sheet->getCell($arrCellName[4].$row)->getValue();
                    $arr_row[$row]['goods_originask'] = $goods_amount; //商品金额
                    //平台交易费 天猫 淘宝
                    $arr_row[$row]['platform_fee'] = $goods_amount*0.05; //商品总金额的5%
                }
                //7 返点积分
                //买家实际支付金额
                if($column==8){
                    echo "<td>$col_val</td>";
                }
                //9买家实际支付积分
                //订单状态
                if($column==10){
                    if(trim($col_val)!="买家已付款，等待卖家发货"){
                        $fund_status = 1;
                        break;
                    }
                    echo "<td>$col_val</td>";
                }
                //买家留言
                if($column==11){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['platform_message'] = $col_val;
                }
                //收货人姓名
                if($column==12){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['consignee'] = $col_val;
                }
                //收货地址
                if($column==13){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['address'] = str_replace("#","",$col_val);
                }
                //运送方式
                if($column==14){
                    echo "<td>$col_val</td>";
                        $arr_row[$row]['shipping_name'] = "中通快递"; //默认固定为中通快递
                }
                //联系电话
                if($column==15){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['tel'] = trim($col_val,"'");
                }
                //联系手机
                if($column==16){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['mobile'] = trim($col_val,"'");
                }
                //订单创建时间
                if($column==17){
                    $date_val = $sheet->getCell($arrCellName[$column].$row)->getFormattedValue();
                    echo "<td>$date_val</td>";
                    //$arr_row[$row]['ordertime'] = $date_val;
                }
                //订单付款时间
                if($column==18){
                    $date_value = $sheet->getCell($arrCellName[$column].$row)->getFormattedValue();
                    $times = strtotime($date_value);
                    $dates = date("Y-m-d H:i:s",$times);
                    echo "<td>$date_value</td>";
                    $arr_row[$row]['ordertime'] = $dates; //订单创建时间，使用的是订单付款时间

                }
                //19宝贝标题
                //20宝贝种类
                //物流单号
                if($column==21){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['shipping_number'] = $col_val;
                }
                //物流公司
                if($column==22){
                    echo "<td>$col_val</td>";
                    //$arr_row['shipping_number'] = $col_val;
                }
                //订单备注
                if($column==23){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['remark'] = $col_val;
                }
                //24宝贝总数量
                //店铺id
                if($column==25){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['shopid'] = $col_val;
                }
                //店铺名称
                if($column==26){
                    echo "<td>$col_val</td>";
                    $arr_row[$row]['shopname'] = $col_val;
                }
                if($column==39){
                    if($col_val&&$col_val!="null"){  //如果修改后的地址存在，则使用该地址
                        $arr_row[$row]['address'] = $col_val;
                    }
                }

            }
            //若该订单为未付款订单，则过滤
            if($fund_status==1){
                unset($arr_row[$row]);
                continue;
            }

            //更新或插入数据库表记录
            echo "<tr/>";
            // print_r($arr_row);exit;
        }
        echo "<table>";
        $json_orders = json_encode($arr_row);
        echo "<br/>";
        echo "<div style=\"color:red;\">需要更新的商品信息为...</div>";
        $sheetOne = $objExcel->getSheet(1);
        $rowsOne = $sheetOne->getHighestRow();
        $colsOne = $sheetOne->getHighestColumn();
        $arrCellNameOne = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
            'AV','AW','AX','AY','AZ','BA','BB','BC','BD','BE','BF');
        $columnsOne = array_search($colsOne, $arrCellNameOne); //获取数组下标最大数
        echo "<table>";
        $tr_titleOne="<tr><td>订单编号</td><td>标题</td><td>价格</td><td>购买数量</td><td>外部系统编号</td><td>商品属性</td>";
        $tr_titleOne.="<td>套餐信息</td><td>备注</td><td>订单状态</td><td>商家编码</td>";
        $tr_titleOne.="</tr>";
        echo $tr_titleOne;
        $arr_rowsOne = array();
        for($r=2;$r<=$rowsOne;$r++) {
            echo "<tr>";
            //列
            for ($c =0; $c <=$columnsOne; $c++) {
                $cellValueOne = $arrCellNameOne[$c].$r; //定位单元格 如：A2
                //获取一行每列的值
                $col_valOne = $sheetOne->getCell($cellValueOne)->getValue();
                //订单编号
                if($c==0){
                    echo "<td>$col_valOne</td>";
                    $arr_rowsOne[$r]['order_sn'] = trim($col_valOne,"=");
                    $arr_rowsOne[$r]['order_sn'] = trim($arr_rowsOne[$r]['order_sn'],'"');
                }
                //标题 应当为商品名称
                if($c==1){
                    echo "<td>$col_valOne</td>";
                    $arr_rowsOne[$r]['goods_name'] = $col_valOne;
                }
                //价格
                if($c==2){
                    echo "<td>$col_valOne</td>";
                    $arr_rowsOne[$r]['goods_price'] = $col_valOne;
                }
                //购买数量
                if($c==3){
                    echo "<td>$col_valOne</td>";
                    $arr_rowsOne[$r]['goods_number'] = $col_valOne;
                }
                //外部系统编号
                if($c==4){
                    echo "<td>$col_valOne</td>";
                    $arr_rowsOne[$r]['originsku'] = $col_valOne;
                }
                //商品属性
                if($c==5){
                    echo "<td>$col_valOne</td>";
                    $arr_rowsOne[$r]['goods_attr'] = $col_valOne;
                }
                //6套餐信息
                if($c==6){
                    echo "<td>$col_valOne</td>";
                }
                //备注
                if($c==7){
                    echo "<td>$col_valOne</td>";
                    $arr_rowsOne[$r]['sale_remark'] = $col_valOne;
                }
                //订单状态
                if($c==8){
                    echo "<td>$col_valOne</td>";
                    //$arr_rowsOne['sale_remark'] = $col_valOne;
                }
                //商家编码
                if($c==9){
                    echo "<td>$col_valOne</td>";
                    $arr_rowsOne[$r]['goods_sn'] = $col_valOne;
                    //查询 商品成本价等相关信息
                    $goodsInfo_sql = "SELECT * FROM db_goods WHERE goods_sku = '{$arr_rowsOne[$r]['goods_sn']}' ";
                    $goods_info = $this->db->query($goodsInfo_sql)->row_array();
                    if($goods_info){
                        $arr_rowsOne[$r]['costprice'] = $goods_info['g_costprice']; //商品成本
                        $arr_rowsOne[$r]['goods_weight'] = $goods_info['g_weight']; //商品重量
                    }else{
                        $arr_rowsOne[$r]['costprice'] = ""; //商品成本
                        $arr_rowsOne[$r]['goods_weight'] = ""; //商品重量
                    }
                }
            }
            echo "</tr>";
        }
        echo "</table>";
        echo "<br/>";
        echo "<br/>";
        echo "<br/>";
        echo "<a href='$url'>点击确定上传</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='/orderlist/orderlist'>返回修改后上传</a>";

        //更新数据库相关表
        $data['orders'] = serialize($arr_row);
        $data['goods'] = serialize($arr_rowsOne);
        $data['createUid'] = $_COOKIE['userid'];
        $data['createUser'] = $_COOKIE['username'];
        $data['addTime']= date("Y-m-d H:i:s");
        $data['timeOut'] = time()+7200; //过期时间 两小时
        //$data['isUpload']  = 0;//默认0，若为1则代表真实上传过
        //$data['del_flag'] = 0; //默认
        $data['token'] = $rand;
        $this->db->insert('tmp_upload_order',$data);

    }
    private function insertTaobaoOrder(& $arr_orders,& $arr_goods,$token){
        $this->load->library('amazondata');
        foreach($arr_orders as $k=>$v){
            $order_row = $k-1;
            $arr_good  = array();
            $arr_order = array();
            //若存在，则更新，否则插入
            $sql_order = "SELECT * FROM db_order_list WHERE tradeid = '{$v['order_sn']}' ";
            $rs_order  = $this->db->query($sql_order)->row_array();
            try {
                $order_length = strlen(trim($v['order_sn']));
                if(!$v['order_sn']){
                    continue;
                }
                /**
                if($order_length!=16){
                echo "<div style='text-align:center;font-size:12px;color:red;'>第" . $order_row . "个订单因订单号不符合要求，无法导入,订单号：{$v['order_sn']}</div>";
                echo "<br/>";
                continue;
                }**/
                if ($rs_order) {
                    //更新订单表
                    continue;
                } else {
                    $this->load->library('amazondata');
                    $arr_order['order_sn'] = $this->amazondata->getNo("",$v['order_sn']);//生成订单序号
                    //插入订单表
                    $arr_order['tradeid'] = $v['order_sn']; //tradeid

                    //固定order_status
                    $arr_order['dates'] = date("Y-m-d");
                    $arr_order['order_source'] = "正常订单";
                    $arr_order['order_status'] = 2; //已支付
                    $arr_order['moneytype'] = "RMB";
                    $arr_order['moneyrate'] = 1;
                    $arr_order['add_time'] = time();

                    //店铺
                    $arr_order['shopid'] = $v['shopId'];
                    $arr_order['shopname'] = $v['shopName'];
                    if($v['oper']){
                        $arr_order['shopoper'] = $v['oper'];
                    }
                    if ($v['platform_message']) {
                        $arr_order['platform_message'] = $v['platform_message'];
                    }
                    if ($v['platformID']) {
                        $arr_order['platformID'] = $v['platformID'];
                    }
                    if ($v['customerid']) {
                        $arr_order['customerid'] = $v['customerid'];
                    }
                    if ($v['shipping_fee']) {
                        //$arr_order['shipping_realfee'] = $v['shipping_realfee'];//正式快递费
                        $arr_order['shipping_fee'] = $v['shipping_fee']; //收取客人快递费RMB
                        $arr_order['shipping_originask'] = $v['shipping_fee'];//原始快递费
                    }
                    if ($v['goods_originask']) {
                        $arr_order['goods_originask'] = $v['goods_originask']-$v['shipping_realfee'];
                        $arr_order['goods_amount'] = $v['goods_originask']-$v['shipping_realfee'];
                        //平台交易费 天猫 淘宝
                        //$arr_order['platform_fee'] = $arr_order['goods_amount']*0.05; //商品总金额的5%
                    }
                    if ($v['consignee']) {
                        $arr_order['consignee'] = $v['consignee'];
                    }
                    if ($v['address']) {
                        $arr_order['country'] = "china";
                        $arr_order['country_code'] = "CN";
                        $arr_order['country_cn'] = "中国";
                        //默认 一号仓发货
                        $arr_order['shipping_status'] = 5;
                        //对地址进行截取
                        $arr_address = explode(" ",$v['address']);
                        $address_len = count($arr_address);
                        if(count($arr_address)>2){
                            $arr_order['province'] = $arr_address[0];
                            $arr_order['city'] = $arr_address[1];
                            $address = "";
                            foreach($arr_address as $kk=>$vv){
                                if($kk>1){
                                    $address.= $vv;
                                }
                            }
                            $arr_order['address'] = $address;
                            $arr_order['zipcode'] = substr($v['address'],-7,-1);

                        }
                    }
                    if ($v['shipping_name']) {
                        $arr_order['shipping_name'] = $v['shipping_name'];
                        $arr_order['shipping_id'] = 25; //中通快递默认 shipping_id 25
                        //计算运费
                    }
                    if ($v['tel']) {
                        $arr_order['tel'] = $v['tel'];
                    }
                    if ($v['mobile']) {
                        $arr_order['mobile'] = $v['mobile'];
                    }
                    if ($v['ordertime']) {
                        $arr_order['ordertime'] = $v['ordertime'];
                    }
                    if ($v['shipping_number']) {
                        $arr_order['shipping_number'] = $v['shipping_number'];
                    }
                    if ($v['remark']) {
                        $arr_order['remark'] = $v['remark'];
                    }
                    if ($v['shopid']) {
                        //$arr_order['shopid'] = $v['shopid'];
                    }
                    if ($v['shopname']) {
                        //$arr_order['shopname'] = $v['shopname'];
                    }
                    $this->db->trans_begin();
                    $this->db->insert('db_order_list', $arr_order);
                    $insert_id = $this->db->insert_id();

                    //更新日志表db_goods_log
                    $imgdata["goods_id"] = $insert_id;	//订单ID db_order_list
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = $_COOKIE['userid'];
                    $imgdata["types"] = 3;
                    $imgdata["content"] = 'excel导入订单，交易ID='.$arr_order['tradeid'];
                    $imgdata["createUser"] =$_COOKIE['username'];
                    $this->db->insert('db_goods_log', $imgdata);


                    //插入商品表
                    foreach ($arr_goods as $key => $value) {
                        if ($value['order_sn']==$v['order_sn']) { //为 db_order_list表中tradeid进行的比较
                            //判断goods_sn是否存在
                            $goods_sql = "SELECT * FROM db_goods WHERE goods_sku = '{$value['goods_sn']}' ";
                            $goods_rs  = $this->db->query($goods_sql)->row_array();
                            if(!$goods_rs){
                                $this->db->update('db_order_list',array('order_status'=>7),array('order_sn'=>$arr_order['order_sn']));
                            }else{
                                $arr_good['goods_id'] = $goods_rs['goods_id'];
                                $arr_good['goods_weight'] = $goods_rs['g_weight']*$value['goods_number'];
                                $weight = $arr_good['goods_weight'];
                                if($weight){
                                    //更新订单重量
                                    $sql_upd = "UPDATE db_order_list SET orderweight = orderweight+$weight WHERE order_sn = '{$arr_order['order_sn']}' ";
                                    $upd_rs = $this->db->query($sql_upd);
                                    //预估重量

                                    //是否计算相关运费 如果只存在20030一个sku，则不计算运费
                                    if($value['goods_sn']=="23030"){
                                        $sql_sn = "SELECT * FROM db_order_sell WHERE order_id = '{$insert_id}' ";
                                        $rs_sn = $this->db->query($sql_sn)->row_array();
                                        if($rs_sn){
                                            //中通快递运费计算 预估运费
                                            $sql_expectfee = "SELECT * FROM db_order_list WHERE order_sn = '{$arr_order['order_sn']}' ";
                                            $rs_expectfee  = $this->db->query($sql_expectfee)->row_array();

                                            $freight = $this->fun->get_Estimate_freight($rs_expectfee['orderweight'],$arr_order['province'],25,"中通快递");
                                            if($freight !="没有填写运费计算公式"){
                                                $this->db->update('db_order_list',array('shipping_expectfee'=>$freight),array('order_sn'=>$arr_order['order_sn']));
                                            }
                                        }

                                    }else{

                                        //中通快递运费计算 预估运费
                                        $sql_expectfee = "SELECT * FROM db_order_list WHERE order_sn = '{$arr_order['order_sn']}' ";
                                        $rs_expectfee  = $this->db->query($sql_expectfee)->row_array();

                                        $freight = $this->fun->get_Estimate_freight($rs_expectfee['orderweight'],$arr_order['province'],25,"中通快递");
                                        if($freight !="没有填写运费计算公式"){
                                            $this->db->update('db_order_list',array('shipping_expectfee'=>$freight),array('order_sn'=>$arr_order['order_sn']));
                                        }
                                    }
                                }
                            }
                            //插入相关商品表
                            $arr_good['order_id'] = $insert_id;
                            $arr_good['goods_name'] = $value['goods_name'];
                            $arr_good['goods_price'] = $value['goods_price'];
                            $arr_good['goods_amount'] = $value['goods_price']*$value['goods_number'];
                            $arr_good['goods_number'] = $value['goods_number'];
                            $arr_good['originsku'] = $value['originsku'];
                            if($value['goods_attr']){
                                $arr_good['goods_attr'] = $value['goods_attr'];
                            }
                            //获取商品的成本价格
                            $factorycode = $this->amazondata->factorycode();
                            $costprice = 0;
                            if(is_numeric($value['goods_sn'])&&preg_match('|^\d{8}$|',$value['goods_sn'])){
                                $goodscode = substr($value['goods_sn'],0,2);
                                if(in_array($goodscode,$factorycode)){
                                    $costprice = $goods_rs['g_costprice'];
                                }
                            }else{
                                //如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
                                if(is_numeric($goods_rs["goods_parent_sku"]) && preg_match('|^\d{8}$|',$goods_rs["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
                                {
                                    $goodscodes  = substr($goods_rs["goods_parent_sku"],0,2);//取开头2位数
                                    if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
                                    {
                                        $costprice = $goods_rs["bulkprice"];	//批量按关联价计算
                                    }
                                }else{
                                    $costprice = $goods_rs["g_costprice"];
                                }
                            }
                            if(!$costprice){
                                $costprice = 0;
                            }
                            $arr_good['costprice'] = $costprice;
                            /**
                            if($value['costprice']){
                                $arr_good['costprice'] = $value['costprice'];
                            }**/
                            if($value['goods_weight']){
                                $arr_good['goods_weight'] = $value['goods_weight'];
                            }
                            if($value['sale_remark']){
                                $arr_good['sale_remark'] = $value['sale_remark'];
                            }
                            if($value['goods_sn']){
                                $arr_good['goods_sn'] = $value['goods_sn'];
                            }
                            $this->db->insert('db_order_sell', $arr_good);

                        }
                    }
                    echo "<div style='text-align:center;font-size:12px;'>第" . $order_row . "个订单以及其商品插入完成,订单号：{$v['order_sn']}</div>";
                    echo "<br/>";
                }
                //$this->db->trans_commit();
            }catch(Exception $e){
                //$this->db->trans_rollback();
                echo "<div style='text-align:center;font-size:12px;color:red;'>第" . $order_row . "个订单以及其商品插入或更新失败".$e->getMessage()."订单号：".$v['order_sn']."</div>";
            }
            //若执行成功，则提交

            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
            }
            else
            {
                $this->db->trans_commit();
            }

        }
        echo "<div style='text-align:center;font-size:24px;color:red;'>数据导入完成...</div>";
        echo "<br/>";
        //更新 isUpload 说明已上传  del_flag 删除标记
        $this->db->update('tmp_upload_order',array('isUpload'=>1,'del_flag'=>1),array('token'=>$token));
    }
    /** 台湾shopee平台相关店铺名 */
    private function importTaiWanOrder($objExcel,$arr_shop){
        $sheet = $objExcel->getSheet(0);
        $rows = $sheet->getHighestRow(); //多少行数据
        $cols = $sheet->getHighestColumn();
        $arrCellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
            'AV','AW','AX','AY','AZ','BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT');
        $columns = array_search($cols, $arrCellName); //获取数组下标最大数
        $rand = date("YmdHis").rand(111111,999999);
        $rand = md5($rand);
        //行
        echo "<div style=\"color:red;\">需要更新的订单信息为...</div>";
        $url = "/orderexcel/ajaxbutton?op=importExcelOrder&token=".$rand;
        echo "<a href='$url'>点击确定上传</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='/orderlist/orderlist'>返回修改后上传</a>";
        echo "<br/>";
        echo "<table>";
        $tr_title="<tr><td>訂單編號</td><td>買家帳號</td><td>訂單成立時間</td><td>訂單小計 (TWD)</td>";
        $tr_title.="<td>買家支付的運費</td><td>訂單總金額</td><td>商品資訊</td><td>收件地址</td>";
        $tr_title.="<td>收件者姓名</td><td>電話號碼</td><td>寄送方式</td><td>買家備註</td>";
        $tr_title.="</tr>";
        echo $tr_title;
        for($row=2;$row<=$rows;$row++){
            echo "<tr>";
            //列
            for($column=0;$column<= $columns;$column++){
                $cellValue = $arrCellName[$column].$row;
                //当前数据名称
                $dataName = $arrCellName[$column]."1";
                $dataName= $sheet->getCell($dataName)->getValue();

                //获取一行每列的值
                $col_val = $sheet->getCell($cellValue)->getValue();
                $col_val = trim($col_val);
                //店铺相关
                $arr_order[$row]['shopId'] = $arr_shop['id'];
                $arr_order[$row]['shopName'] = $arr_shop['name'];
                $arr_order[$row]['oper'] = $arr_shop['updateoper']; //店铺负责人
                $arr_order[$row]['platfromname'] = $arr_shop['platfromname']; //平台名
                $arr_order[$row]['platfrom'] = $arr_shop['platfrom']; //平台id


                //訂單編號.
                if($column==0){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['order_sn'] = $col_val;
                }
                //買家帳號
                if($column==3){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['customerid'] = $col_val;
                }
                //訂單成立時間
                if($column==4){
                    $date_value = $sheet->getCell($arrCellName[$column].$row)->getFormattedValue();
                    $times = strtotime($date_value);
                    $dates = date("Y-m-d H:i:s",$times);
                    echo "<td>$dates</td>";
                    $arr_order[$row]['ordertime'] = $dates;
                }
                //訂單小計
                if($column==6){
                    echo "<td>$col_val</td>";
                    //商品金额
                    $goods_amount = $col_val;
                    $arr_order[$row]['goods_originask'] = $goods_amount; //商品金额
                    //平台交易费 天猫 淘宝
                    $arr_order[$row]['platform_fee'] = $goods_amount*0.03; //商品总金额的5%
                    //$arr_row['shipping_realfee'] = $col_val;
                }
                //買家支付的運費
                if($column==7){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['shipping_originask'] = $col_val;
                    $arr_order[$row]['shipping_fee'] = $col_val;
                }
                //訂單總金額
                if($column==8){
                    //总金额
                    echo "<td>$col_val</td>";
                }
                //商品資訊
                if($column==9){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['goodsinfo'] = $col_val;
                }
                //收件地址
                if($column==10){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['address'] = $col_val;
                }
                //收件者姓名
                if($column==15){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['consignee'] = $col_val;

                }
                //電話號碼
                if($column==16){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['tel'] = $col_val;
                }
                //寄送方式
                if($column==17){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['shipping_name'] = $col_val;
                }
                //買家備註
                if($column==26){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['platform_message'] = $col_val;
                }
            }
            //更新或插入数据库表记录
            echo "<tr/>";
            // print_r($arr_row);exit;
        }
        echo "<table>";
        echo "<br/>";
        echo "<br/>";
        echo "<a href='$url'>点击确定上传</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='/orderlist/orderlist'>返回修改后上传</a>";
        echo "<br/><br/>";
        //更新数据库相关表
        $data['orders'] = serialize($arr_order);
        //$data['goods'] = serialize($arr_goods); 都在订单表里面
        $data['createUid'] = $_COOKIE['userid'];
        $data['createUser'] = $_COOKIE['username'];
        $data['addTime']= date("Y-m-d H:i:s");
        $data['timeOut'] = time()+7200; //过期时间 两小时
        //$data['isUpload']  = 0;//默认0，若为1则代表真实上传过
        //$data['del_flag'] = 0; //默认
        $data['token'] = $rand;
        $this->db->insert('tmp_upload_order',$data);
    }
    private function insertTaiWanOrder(& $arr_orders,$token,$moneyType){
        $this->load->library('amazondata');
        $sql_rate = "SELECT * FROM d_moneyrate WHERE name = '{$moneyType}' ";
        $rs_rate  = $this->db->query($sql_rate)->row_array();
        //循环订单列表
        foreach($arr_orders as $k=>$v){
            $order_row = $k-1;
            $arr_good  = array();
            $arr_order = array();
            //若存在，则更新，否则插入
            $sql_order = "SELECT * FROM db_order_list WHERE tradeid = '{$v['order_sn']}' ";
            $rs_order  = $this->db->query($sql_order)->row_array();
            try {
                $this->db->trans_begin();
                if(!$v['order_sn']){
                    continue;
                }
                if ($rs_order) {
                    continue;  //重复交易号，不用再次导入
                } else {
                    //$this->load->library('amazondata');
                    $arr_order['order_sn'] = $this->amazondata->getNo("",$v['order_sn']);//生成订单序号
                    //插入订单表
                    $arr_order['tradeid'] = $v['order_sn']; //tradeid
                    //固定order_status
                    $arr_order['dates'] = date("Y-m-d");
                    $arr_order['order_source'] = "正常订单";
                    $arr_order['order_status'] = 2; //已支付

                    $arr_order['moneyrate'] = $rs_rate['rate']; //当前相当于人民币汇率
                    if ($v['platfrom']) {
                        $arr_order['platformID'] = $v['platfrom'];
                    }
                    if($v['platform_message']){
                        $arr_order['remark'] = $v['platform_message']; //默认
                    }
                    //台湾省的店铺
                    $arr_order['country_cn'] = "中国";
                    $arr_order['country'] = "china";
                    $arr_order['country_code'] = "CN";
                    $arr_order['province'] = "台湾省";
                    $arr_order['moneytype'] = "TWD"; //台币
                    $arr_order['add_time'] = time();

                    //默认快递方式
                    $arr_order['shipping_name'] = "圆通台湾";
                    $arr_order['shipping_id'] = 41;

                    $arr_order['moneyrate'] = $rs_rate['rate'];

                    //店铺
                    $arr_order['shopid'] = $v['shopId'];
                    $arr_order['shopname'] = $v['shopName'];
                    if($v['oper']){
                        $arr_order['shopoper'] = $v['oper'];
                    }
                    if ($v['customerid']) {
                        $arr_order['customerid'] = $v['customerid'];
                    }
                    if ($v['shipping_fee']) {
                        $arr_order['shipping_fee'] = $v['shipping_fee']*$rs_rate['rate']; //收取客人快递费RMB
                        $arr_order['shipping_originask'] = $v['shipping_fee'];//原始快递费
                    }
                    if ($v['goods_originask']) {
                        $arr_order['goods_originask'] = $v['goods_originask'];
                        $arr_order['goods_amount'] = $v['goods_originask']*$rs_rate['rate'];
                        //平台交易费
                        $arr_order['platform_fee'] = $arr_order['goods_amount']*0.03; //商品总金额的15% 亚马逊 日本都那么多

                        $arr_order['pay_fee']  = $arr_order['goods_amount']*0.005; //付款交易费
                    }
                    if ($v['consignee']) {
                        $arr_order['consignee'] = $v['consignee'];
                    }
                    if ($v['address']) {
                        //对地址进行截取
                        $arr_order['address'] = $v['address'];
                    }
                    if ($v['tel']) {
                        $arr_order['tel'] = $v['tel'];
                    }
                    if ($v['ordertime']) {
                        $arr_order['ordertime'] = $v['ordertime'];
                    }

                    $this->db->insert('db_order_list', $arr_order);
                    $insert_id = $this->db->insert_id();

                    //更新日志表db_goods_log
                    $imgdata["goods_id"] = $insert_id;	//订单ID db_order_list
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = $_COOKIE['userid'];
                    $imgdata["types"] = 3;
                    //$imgdata["content"] = 'excel导入订单，订单id为：'.$insert_id;
                    $imgdata["content"] = 'excel导入订单，交易ID='.$arr_order['tradeid'];
                    $imgdata["createUser"] =$_COOKIE['username'];
                    $this->db->insert('db_goods_log', $imgdata);

                    //插入商品表
                    if ($insert_id) {
                        //获取商品信息
                        $goodsinfo = str_replace("，",",",$v['goodsinfo']); //商品资讯
                        $goodsinfo = str_replace("：",":",$goodsinfo);
                        $arr_goodsinfo = explode(";",$goodsinfo);
                        //Array ( [0] => [1] 商品名稱:音速小子兒童超萌遮陽帽 [1] => 商品選項名稱: [2] => 價格: $ 310
                        // [3] => 數量: 1 [4] => 商品選項貨號: [5] => 主商品貨號: 306672 [6] => )
                        $str_goods_sn = explode(":",$arr_goodsinfo[5]);
                        $v['goods_sn'] = trim($str_goods_sn[1]);

                        $int_goods_num = explode(":",$arr_goodsinfo[3]);
                        $v['goods_number'] = trim($int_goods_num[1]);

                        $str_goods_name = explode(":",$arr_goodsinfo[1]);
                        $v['goods_name'] = $str_goods_name[1];


                        //判断goods_sn是否存在
                        $goods_sql = "SELECT * FROM db_goods WHERE goods_sku = '{$v['goods_sn']}' ";
                        $goods_rs  = $this->db->query($goods_sql)->row_array();
                        if(!$goods_rs){
                            $this->db->update('db_order_list',array('order_status'=>7),array('tradeid'=>$v['order_sn']));
                        }else{
                            $arr_good['goods_id'] = $goods_rs['goods_id'];
                            $arr_good['goods_weight'] = $goods_rs['g_weight']*$v['goods_number'];
                            $arr_good['originsku'] = $goods_rs['goods_parent_sku'];

                            $weight = $arr_good['goods_weight'];
                            $sql_upd = "UPDATE db_order_list SET orderweight = orderweight+$weight WHERE tradeid = '{$v['order_sn']}' ";
                            $upd_rs = $this->db->query($sql_upd);

                            //获取商品的成本价格
                            $factorycode = $this->amazondata->factorycode();
                            if(is_numeric($v['goods_sn'])&&preg_match('|^\d{8}$|',$v['goods_sn'])){
                                $goodscode = substr($v['goods_sn'],0,2);
                                if(in_array($goodscode,$factorycode)){
                                    $costprice = $goods_rs['g_costprice'];
                                }
                            }else{
                                //如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
                                if(is_numeric($goods_rs["goods_parent_sku"]) && preg_match('|^\d{8}$|',$goods_rs["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
                                {
                                    $goodscodes  = substr($goods_rs["goods_parent_sku"],0,2);//取开头2位数
                                    if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
                                    {
                                        $costprice = $goods_rs["bulkprice"];	//批量按关联价计算
                                    }
                                }else{
                                    $costprice = $goods_rs["g_costprice"];
                                }
                            }
                            $arr_good['costprice'] = $costprice;
                        }
                        //插入相关商品表
                        $arr_good['order_id'] = $insert_id;
                        if($v['goods_name']){
                            $arr_good['goods_name'] = $v['goods_name'];
                        }
                        if($v['goods_originask']){
                            $arr_good['goods_price'] = ($v['goods_originask']*$rs_rate['rate'])/$v['goods_number'];
                            $arr_good['originsellprice'] = $v['goods_originask']/$v['goods_number'];
                        }
                        $arr_good['goods_amount'] = $v['goods_originask']*$rs_rate['rate'];
                        $arr_good['goods_number'] = $v['goods_number'];
                        $arr_good['goods_sn'] = $v['goods_sn'];
                        $this->db->insert('db_order_sell', $arr_good);
                    }
                    echo "<div style='text-align:center;font-size:12px;'>第" . $order_row . "个订单以及其商品插入完成,订单号：{$v['order_sn']}</div>";
                    echo "<br/>";
                }
                //$this->db->trans_commit();
            }catch(Exception $e){
                //$this->db->trans_rollback();
                echo "<div style='text-align:center;font-size:12px;color:red;'>第" . $order_row . "个订单以及其商品插入或更新失败".$e->getMessage()."订单号：".$v['order_sn']."</div>";
            }
            //若执行成功，则提交

            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
            }
            else
            {
                $this->db->trans_commit();
            }

        }
        echo "<div style='text-align:center;font-size:24px;color:red;'>数据导入完成...</div>";
        echo "<br/>";
        //更新 isUpload 说明已上传  del_flag 删除标记
        $this->db->update('tmp_upload_order',array('isUpload'=>1,'del_flag'=>1),array('token'=>$token));
    }

    /** 速卖通平台相关店铺名 */
    private function importAliexpressOrder($objExcel,$arr_shop){
        $sheet = $objExcel->getSheet(0);
        $rows = $sheet->getHighestRow(); //多少行数据
        $cols = $sheet->getHighestColumn();
        $arrCellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
            'AV','AW','AX','AY','AZ','BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT');
        $columns = array_search($cols, $arrCellName); //获取数组下标最大数
        $rand = date("YmdHis").rand(111111,999999);
        $rand = md5($rand);
        //行
        echo "<div style=\"color:red;\">需要更新的订单信息为...</div>";
        $url = "/orderexcel/ajaxbutton?op=importExcelOrder&token=".$rand;
        echo "<a href='$url'>点击确定上传</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='/orderlist/orderlist'>返回修改后上传</a>";
        echo "<br/>";
        echo "<table>";
        $tr_title="<tr><td>订单号</td><td>订单状态</td><td>买家名称</td><td>下单时间</td>";
        $tr_title.="<td>付款时间</td><td>产品总金额</td><td>物流费用</td><td>订单金额</td>";
        $tr_title.="<td>产品信息</td><td>订单备注</td><td>收货地址</td><td>收货人姓名</td><td>收货国家</td>";
        $tr_title.="<td>州/省</td><td>城市</td><td>地址</td><td>邮编</td>";
        $tr_title.="<td>联系电话</td><td>手机</td><td>发货期限</td>";
        $tr_title.="</tr>";
        echo $tr_title;
        for($row=2;$row<=$rows;$row++){
            echo "<tr>";
            //列
            for($column=0;$column<= $columns;$column++){
                $cellValue = $arrCellName[$column].$row;
                //当前数据名称
                $dataName = $arrCellName[$column]."1";
                $dataName= $sheet->getCell($dataName)->getValue();

                //获取一行每列的值
                $col_val = $sheet->getCell($cellValue)->getValue();
                $col_val = trim($col_val);
                //店铺相关
                $arr_order[$row]['shopId'] = $arr_shop['id'];
                $arr_order[$row]['shopName'] = $arr_shop['name'];
                $arr_order[$row]['oper'] = $arr_shop['updateoper']; //店铺负责人
                $arr_order[$row]['platfromname'] = $arr_shop['platfromname']; //平台名
                $arr_order[$row]['platfrom'] = $arr_shop['platfrom']; //平台id


                //订单号
                if($column==0){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['order_sn'] = $col_val;
                }
                //订单状态
                if($column==1){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['orderstatus'] = $col_val;
                }
                //买家名称
                if($column==3){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['customerid'] = $col_val;
                }
                //下单时间
                if($column==4){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['ordertime'] = $col_val;
                }
                //付款时间
                if($column==5){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['paytime'] = $col_val;
                }
                //产品总金额
                if($column==6){
                    echo "<td>$col_val</td>";
                    //商品金额
                    $goods_amount = $col_val;
                    $arr_order[$row]['goods_originask'] = $goods_amount; //商品金额
                    //平台交易费
                    //$arr_order[$row]['platform_fee'] = $goods_amount*0.03; //商品总金额的5%
                    //$arr_row['shipping_realfee'] = $col_val;
                }
                //物流费用
                if($column==7){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['shipping_originask'] = $col_val;
                    $arr_order[$row]['shipping_fee'] = $col_val;
                }
                //订单金额 （同商品金额)
                if($column==8){
                    //总金额
                    echo "<td>$col_val</td>";
                }
                //产品信息
                if($column==10){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['goodsinfo'] = $col_val;
                }
                //订单备注
                if($column==11){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['remark'] = $col_val;
                }
                //收货地址  包括 国家 城市 等地址
                if($column==12){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['receiveaddress'] = $col_val;
                }
                //收货人姓名
                if($column==13){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['consignee'] = $col_val;
                }
                //收货国家
                if($column==14){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['country'] = $col_val;
                }
                //州/省
                if($column==15){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['province'] = $col_val;
                }
                //城市
                if($column==16){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['city'] = $col_val;
                }
                //地址
                if($column==17){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['address'] = $col_val;
                }
                //邮编
                if($column==18){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['zipcode'] = $col_val;

                }
                //联系电话
                if($column==19){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['tel'] = $col_val;
                }
                //手机
                if($column==20){
                    echo "<td>$col_val</td>";
                    $arr_order[$row]['mobile'] = $col_val;
                }
                //发货期限
                if($column==22){
                    echo "<td>$col_val</td>";
                }
            }
            //更新或插入数据库表记录
            echo "<tr/>";
            // print_r($arr_row);exit;
        }
        echo "<table>";
        echo "<br/>";
        echo "<br/>";
        echo "<a href='$url'>点击确定上传</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='/orderlist/orderlist'>返回修改后上传</a>";
        echo "<br/><br/>";
        //更新数据库相关表
        $data['orders'] = serialize($arr_order);
        //$data['goods'] = serialize($arr_goods); 都在订单表里面
        $data['createUid'] = $_COOKIE['userid'];
        $data['createUser'] = $_COOKIE['username'];
        $data['addTime']= date("Y-m-d H:i:s");
        $data['timeOut'] = time()+7200; //过期时间 两小时
        //$data['isUpload']  = 0;//默认0，若为1则代表真实上传过
        //$data['del_flag'] = 0; //默认
        $data['token'] = $rand;
        $this->db->insert('tmp_upload_order',$data);
    }
    private function insertAliexpressOrder(& $arr_orders,$token,$moneyType){
        $this->load->library('amazondata');
        $sql_rate = "SELECT * FROM d_moneyrate WHERE name = '{$moneyType}' ";
        $rs_rate  = $this->db->query($sql_rate)->row_array();
        //循环订单列表
        foreach($arr_orders as $k=>$v){
            $order_row = $k-1;
            $arr_good  = array();
            $arr_order = array();
            if(!$v['order_sn']){
                continue;
            }
            if($v['orderstatus'] != "等待您发货"){
                continue;
            }
            //若存在，则更新，否则插入
            $sql_order = "SELECT * FROM db_order_list WHERE tradeid = '{$v['order_sn']}' ";
            $rs_order  = $this->db->query($sql_order)->row_array();
            try {

                if ($rs_order) {
                    continue;  //重复交易号，不用再次导入
                } else {
                    $this->db->trans_begin();
                    //$this->load->library('amazondata');
                    $arr_order['order_sn'] = $this->amazondata->getNo('Aliexpress',$v['order_sn']);//生成订单序号
                    //插入订单表
                    $arr_order['tradeid'] = $v['order_sn']; //tradeid
                    //固定order_status
                    $arr_order['dates'] = date("Y-m-d");
                    $arr_order['order_source'] = "正常订单";
                    $arr_order['order_status'] = 2; //已支付

                    $arr_order['moneyrate'] = $rs_rate['rate']; //当前相当于人民币汇率
                    if ($v['platfrom']) {
                        $arr_order['platformID'] = $v['platfrom'];
                    }
                    if($v['platform_message']){
                        $arr_order['remark'] = $v['remark']; //默认
                    }


                    $arr_order['country'] = $v['country'];
                    $sql_country = "SELECT * FROM d_country WHERE countrynamecn = '{$arr_order['country']}' ";
                    $rs_country  = $this->db->query($sql_country)->row_array();
                    if(!$rs_country){
                        $arr_order['country'] = str_replace(" ","",$v['country']);
                        $sql_country = "SELECT * FROM d_country WHERE countrynamecn = '{$arr_order['country']}' ";
                        $rs_country  = $this->db->query($sql_country)->row_array();
                    }

                    $arr_order['country_cn'] = $rs_country['countrynameen']?$rs_country['countrynameen']:"";
                    $arr_order['country_code'] = $rs_country['countryid']?$rs_country['countryid']:"";
                    $arr_order['province'] = $v['province'];
                    $arr_order['city'] = $v['city'];
                    $arr_order['zipcode'] = $v['zipcode'];
                    $arr_order['moneytype'] = "USD"; //美金
                    $arr_order['add_time'] = time();

                    $arr_order['moneyrate'] = $rs_rate['rate'];

                    //店铺
                    $arr_order['shopid'] = $v['shopId'];
                    $arr_order['shopname'] = $v['shopName'];
                    if($v['oper']){
                        $arr_order['shopoper'] = $v['oper'];
                    }
                    if ($v['customerid']) {
                        $arr_order['customerid'] = $v['customerid'];
                    }
                    if ($v['shipping_fee']) {
                        $arr_order['shipping_fee'] = $v['shipping_fee']*$rs_rate['rate']; //收取客人快递费RMB
                        $arr_order['shipping_originask'] = $v['shipping_fee'];//原始快递费
                    }else{
                        $v['shipping_fee'] = 0;
                    }

                    if ($v['goods_originask']) {
                        $arr_order['goods_originask'] = $v['goods_originask']-$v['shipping_fee'];
                        $arr_order['goods_amount'] = $v['goods_originask']*$rs_rate['rate'];
                        $v['goods_originask'] = $v['goods_originask']-$v['shipping_fee'];
                        $v['goods_amount'] = $v['goods_originask']*$rs_rate['rate'];
                        //平台交易费
                        $arr_order['platform_fee'] = $arr_order['goods_amount']*0.15; //商品总金额的15%

                        $arr_order['pay_fee']  = $arr_order['goods_amount']*0.015; //付款交易费
                    }
                    if ($v['consignee']) {
                        $arr_order['consignee'] = $v['consignee'];
                    }
                    if ($v['address']) {
                        //对地址进行截取
                        $arr_order['address'] = $v['address'];
                    }
                    $tel = "";
                    if ($v['tel']) {
                        $tel = str_replace("null","",trim($v['tel']));
                        if(strlen($tel)<5){
                        }else{
                            $arr_order['tel'] = $tel;
                        }
                    }
                    if ($v['mobile']) {
                        if(strlen($tel)>5){
                            $arr_order['mobile'] = $v['mobile'];
                        }else{
                            $arr_order['mobile'] = $tel.$v['mobile'];
                        }
                    }
                    if ($v['ordertime']) {
                        $arr_order['ordertime'] = $v['ordertime'];
                    }

                    $this->db->insert('db_order_list', $arr_order);
                    $insert_id = $this->db->insert_id();

                    //更新日志表db_goods_log
                    $imgdata["goods_id"] = $insert_id;	//订单ID db_order_list
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = $_COOKIE['userid'];
                    $imgdata["types"] = 3;
                    //$imgdata["content"] = 'excel导入订单，订单id为：'.$insert_id;
                    $imgdata["content"] = 'excel导入订单，交易ID='.$arr_order['tradeid'];
                    $imgdata["createUser"] =$_COOKIE['username'];
                    $this->db->insert('db_goods_log', $imgdata);

                    //插入商品表
                    if ($insert_id) {

                        /**只需要 商品名 商品sku 商品数量
                        $str_content = "【1】 Thor 3 Costume The Dark World Loki Cosplay Costume Halloween Carnival Costume";
                        $str_content.="(产品属性:Size:L)";
                        $str_content .= "(商家编码:16223-L)(产品数量:1 set)";

                        $str_content .= "【2】 Captain America Costume Avengers Age of Ultron Captain America 2 Costume Steve Rogers Cosplay Costume";
                        $str_content.="(产品属性:Color:Men、Size:L)";
                        $str_content .= "(商家编码:16385-L)(产品数量:1 set)";
                         * */
                        $arr_goodsinfo = explode("【",trim($v['goodsinfo']));
                        $arr_goodsinfo = array_filter($arr_goodsinfo);
                        $cost_price = 0;
                        $div_price = 0;
                        if(count($arr_goodsinfo)>1){
                            foreach($arr_goodsinfo as $ke=>$ve){
                                $str_goods = trim($ve);
                                //商品数量
                                $str_tmp_num = str_replace(")",",",strstr($str_goods,"产品数量:"));
                                $arr_tmp = explode(":",$str_tmp_num);
                                $arr_goods_num = explode(" ",$arr_tmp[1]);
                                $ve['goods_number'] = trim($arr_goods_num[0]);

                                //商品sku信息
                                if(strpos($str_goods,"(商家编码:")){
                                    $b = mb_strpos($str_goods,"(商家编码:") + mb_strlen("(商家编码:");
                                    $e = mb_strpos($str_goods,"(产品数量:") - $b;
                                    $goods_sn = mb_substr($str_goods,$b,$e);
                                    $ve['goods_sn'] = str_replace(")","",trim($goods_sn));
                                }else{
                                    $ve['goods_sn'] = "";
                                }

                                //判断goods_sn是否存在
                                $goods_sql = "SELECT * FROM db_goods WHERE goods_sku = '{$ve['goods_sn']}' ";
                                $goods_rs  = $this->db->query($goods_sql)->row_array();
                                $costprice = 0;
                                if(!$goods_rs){
                                }else{
                                    //获取商品的成本价格
                                    $factorycode = $this->amazondata->factorycode();
                                    if(is_numeric($ve['goods_sn'])&&preg_match('|^\d{8}$|',$ve['goods_sn'])){
                                        $goodscode = substr($ve['goods_sn'],0,2);
                                        if(in_array($goodscode,$factorycode)){
                                            $costprice = $goods_rs['g_costprice'];
                                        }
                                    }else{
                                        //如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
                                        if(is_numeric($goods_rs["goods_parent_sku"]) && preg_match('|^\d{8}$|',$goods_rs["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
                                        {
                                            $goodscodes  = substr($goods_rs["goods_parent_sku"],0,2);//取开头2位数
                                            if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
                                            {
                                                $costprice = $goods_rs["bulkprice"];	//批量按关联价计算
                                            }
                                        }else{
                                            $costprice = $goods_rs["g_costprice"];
                                        }
                                    }
                                }
                                $cost_price = $cost_price+$costprice*$ve['goods_number'];
                            }
                            if($cost_price>0){
                                $div_price = round($v['goods_originask']/$cost_price,2);
                            }
                        }

                        foreach($arr_goodsinfo as $key=>$value){
                            $str_goods = trim($value);
                            //商品名称
                            $str_goods_name = mb_substr(strstr($str_goods,"(",true),2);
                            $v['goods_name'] = $str_goods_name;

                            //商品数量
                            $str_tmp_num = str_replace(")",",",strstr($str_goods,"产品数量:"));
                            $arr_tmp = explode(":",$str_tmp_num);
                            $arr_goods_num = explode(" ",$arr_tmp[1]);
                            $v['goods_number'] = trim($arr_goods_num[0]);

                            //商品sku信息
                            if(strpos($str_goods,"(商家编码:")){
                                $b = mb_strpos($str_goods,"(商家编码:") + mb_strlen("(商家编码:");
                                $e = mb_strpos($str_goods,"(产品数量:") - $b;
                                $goods_sn = mb_substr($str_goods,$b,$e);
                                $v['goods_sn'] = str_replace(")","",trim($goods_sn));
                            }else{
                                $v['goods_sn'] = "";
                            }

                            //判断goods_sn是否存在
                            $goods_sql = "SELECT * FROM db_goods WHERE goods_sku = '{$v['goods_sn']}' ";
                            $goods_rs  = $this->db->query($goods_sql)->row_array();
                            if(!$goods_rs){
                                $this->db->update('db_order_list',array('order_status'=>7),array('tradeid'=>$v['order_sn']));
                            }else{
                                $arr_good['goods_id'] = $goods_rs['goods_id'];
                                $arr_good['goods_weight'] = $goods_rs['g_weight']*$v['goods_number'];
                                $arr_good['originsku'] = $goods_rs['goods_parent_sku'];

                                $weight = $arr_good['goods_weight'];
                                $sql_upd = "UPDATE db_order_list SET orderweight = orderweight+$weight WHERE tradeid = '{$v['order_sn']}' ";
                                $upd_rs = $this->db->query($sql_upd);

                                //获取商品的成本价格
                                $factorycode = $this->amazondata->factorycode();
                                if(is_numeric($v['goods_sn'])&&preg_match('|^\d{8}$|',$v['goods_sn'])){
                                    $goodscode = substr($v['goods_sn'],0,2);
                                    if(in_array($goodscode,$factorycode)){
                                        $costprice = $goods_rs['g_costprice'];
                                    }
                                }else{
                                    //如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
                                    if(is_numeric($goods_rs["goods_parent_sku"]) && preg_match('|^\d{8}$|',$goods_rs["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
                                    {
                                        $goodscodes  = substr($goods_rs["goods_parent_sku"],0,2);//取开头2位数
                                        if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
                                        {
                                            $costprice = $goods_rs["bulkprice"];	//批量按关联价计算
                                        }
                                    }else{
                                        $costprice = $goods_rs["g_costprice"];
                                    }
                                }
                                $arr_good['costprice'] = $costprice;
                            }
                            if(!$arr_good['costprice']){
                                $arr_good['costprice'] = 0;
                            }
                            //插入相关商品表
                            $arr_good['order_id'] = $insert_id;
                            if($v['goods_name']){
                                $arr_good['goods_name'] = $v['goods_name'];
                            }
                            //若存在多个商品
                            if(count($arr_goodsinfo)>1){
                                if($v['goods_originask']){
                                    $arr_good['originsellprice'] = $div_price*$arr_good['costprice']*$v['goods_number'];
                                    $arr_good['goods_price'] = $div_price*$rs_rate['rate'];
                                }
                                $arr_good['goods_amount'] = $div_price*$rs_rate['rate']*$v['goods_number'];

                            }else{
                                if($v['goods_originask']){
                                    $arr_good['goods_price'] = ($v['goods_originask']*$rs_rate['rate'])/$v['goods_number'];
                                    $arr_good['originsellprice'] = $v['goods_originask']/$v['goods_number'];
                                }
                                $arr_good['goods_amount'] = $v['goods_originask']*$rs_rate['rate'];
                            }
                            $arr_good['goods_number'] = $v['goods_number'];
                            $arr_good['goods_sn'] = $v['goods_sn'];
                            $this->db->insert('db_order_sell', $arr_good);


                        }




                    }
                    echo "<div style='text-align:center;font-size:12px;'>第" . $order_row . "个订单以及其商品插入完成,订单号：{$v['order_sn']}</div>";
                    echo "<br/>";
                    if ($this->db->trans_status() === FALSE)
                    {
                        $this->db->trans_rollback();
                    }
                    else
                    {
                        $this->db->trans_commit();
                    }
                }
                //$this->db->trans_commit();
            }catch(Exception $e){
                //$this->db->trans_rollback();
                echo "<div style='text-align:center;font-size:12px;color:red;'>第" . $order_row . "个订单以及其商品插入或更新失败".$e->getMessage()."订单号：".$v['order_sn']."</div>";
            }
            //若执行成功，则提交

        }
        echo "<div style='text-align:center;font-size:24px;color:red;'>数据导入完成...</div>";
        echo "<br/>";
        //更新 isUpload 说明已上传  del_flag 删除标记
        $this->db->update('tmp_upload_order',array('isUpload'=>1,'del_flag'=>1),array('token'=>$token));
    }
}
